/**
 * eventChangeDispatcher tests (D-04, D-02/D-03 actor naming — IN-01 fix).
 *
 * Asserts that dispatchEventChange:
 *   - Fires for new events (operation='create')
 *   - Fires for updated events with meaningful changes: time/date/title/location (D-04)
 *   - Does NOT fire for description-only edits (D-04)
 *   - Excludes the actor's own push subscriptions (D-03)
 *   - Names the actor in the notification title (IN-01 / D-02/D-03)
 *   - Falls back to 'A family member' when the actor row is missing (IN-01)
 *
 * Run: pnpm --filter @familysync/api exec vitest run tests/lib/eventChangeDispatcher.test.ts
 */

import { describe, it, expect, vi, beforeEach } from 'vitest';

// Mock DB — the factory is hoisted; per-test configuration uses mockReturnValueOnce
vi.mock('../../src/db/client.js', () => ({
  db: {
    select: vi.fn(),
  },
}));

// Mock pushDispatcher
vi.mock('../../src/lib/pushDispatcher.js', () => ({
  dispatchPush: vi.fn().mockResolvedValue(undefined),
}));

// ---------------------------------------------------------------------------
// Helper: configure db.select for two sequential calls used by dispatchEventChange.
//
// dispatchEventChange calls Promise.all([actorQuery, subsQuery]):
//   1st select → actor name query: .from().where().limit() → [{ displayName }] | []
//   2nd select → subscriptions query: .from().where() → sub rows
//
// We configure the mock BEFORE importing eventChangeDispatcher.js (since each
// test does vi.resetModules + fresh import).
// ---------------------------------------------------------------------------
function setupDbMock(
  db: { select: ReturnType<typeof vi.fn> },
  actorDisplayName: string | null,
  subRows: Array<{ id: number; userId: number; endpoint: string; p256dh: string; auth: string }>,
) {
  db.select
    // 1st call: actor name query (select.from.where.limit)
    .mockReturnValueOnce({
      from: vi.fn().mockReturnValue({
        where: vi.fn().mockReturnValue({
          limit: vi
            .fn()
            .mockResolvedValue(
              actorDisplayName !== null ? [{ displayName: actorDisplayName }] : [],
            ),
        }),
      }),
    })
    // 2nd call: subscriptions query (select.from.where)
    .mockReturnValueOnce({
      from: vi.fn().mockReturnValue({
        where: vi.fn().mockResolvedValue(subRows),
      }),
    });
}

describe('eventChangeDispatcher — trigger conditions (D-04)', () => {
  beforeEach(() => {
    // resetAllMocks clears call history AND resets mockReturnValueOnce queues,
    // preventing leaked once-queues from test N polluting test N+1.
    vi.resetAllMocks();
    vi.resetModules();
  });

  it('dispatches for a new event (operation=create)', async () => {
    const { db } = await import('../../src/db/client.js');
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    const { dispatchEventChange } = await import('../../src/lib/eventChangeDispatcher.js');

    const otherUserSub = {
      id: 2,
      userId: 2,
      endpoint: 'https://push.example.com/sub/2',
      p256dh: 'x',
      auth: 'y',
    };
    setupDbMock(vi.mocked(db), 'Lucas', [otherUserSub]);

    await dispatchEventChange(
      { uid: 'new-event-uid', title: 'Doctor appointment', operation: 'create' },
      /* actorUserId */ 1,
    );

    expect(vi.mocked(dispatchPush)).toHaveBeenCalled();
  });

  it('dispatches for an event with a title change', async () => {
    const { db } = await import('../../src/db/client.js');
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    const { dispatchEventChange } = await import('../../src/lib/eventChangeDispatcher.js');

    const otherUserSub = {
      id: 2,
      userId: 2,
      endpoint: 'https://push.example.com/sub/2',
      p256dh: 'x',
      auth: 'y',
    };
    setupDbMock(vi.mocked(db), 'Lucas', [otherUserSub]);

    await dispatchEventChange(
      {
        uid: 'event-uid-1',
        title: 'Renamed Event',
        operation: 'update',
        changedFields: ['title'],
      },
      /* actorUserId */ 1,
    );

    expect(vi.mocked(dispatchPush)).toHaveBeenCalled();
  });

  it('does NOT dispatch for a description-only edit (D-04)', async () => {
    const { db } = await import('../../src/db/client.js');
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    const { dispatchEventChange } = await import('../../src/lib/eventChangeDispatcher.js');

    // isMeaningfulChange returns false before DB is queried — select won't be called.
    // Set up mock anyway as a no-op guard.
    setupDbMock(vi.mocked(db), 'Lucas', [
      { id: 2, userId: 2, endpoint: 'https://push.example.com/sub/2', p256dh: 'x', auth: 'y' },
    ]);

    await dispatchEventChange(
      {
        uid: 'event-uid-2',
        title: 'Team lunch',
        operation: 'update',
        changedFields: ['description'], // description-only — must NOT fire
      },
      /* actorUserId */ 1,
    );

    expect(vi.mocked(dispatchPush)).not.toHaveBeenCalled();
  });

  it('excludes the actor user subscriptions from dispatch (D-03)', async () => {
    const { db } = await import('../../src/db/client.js');
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    const { dispatchEventChange } = await import('../../src/lib/eventChangeDispatcher.js');

    // DB's ne() filter already excludes the actor; simulate that the DB returns
    // only the actor's own sub (userId=1) to test the application-level guard.
    setupDbMock(vi.mocked(db), 'Lucas', [
      { id: 1, userId: 1, endpoint: 'https://push.example.com/sub/1', p256dh: 'x', auth: 'y' },
    ]);

    await dispatchEventChange(
      { uid: 'event-uid-3', title: 'Soccer practice', operation: 'create' },
      /* actorUserId */ 1, // actor is userId=1 — their subscription must be excluded
    );

    // No subscriptions remain after excluding the actor — nothing dispatched
    expect(vi.mocked(dispatchPush)).not.toHaveBeenCalled();
  });

  it('names the actor in the notification title (IN-01 / D-02/D-03)', async () => {
    const { db } = await import('../../src/db/client.js');
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    const { dispatchEventChange } = await import('../../src/lib/eventChangeDispatcher.js');

    const otherUserSub = {
      id: 2,
      userId: 2,
      endpoint: 'https://push.example.com/sub/2',
      p256dh: 'x',
      auth: 'y',
    };
    setupDbMock(vi.mocked(db), 'Lucas', [otherUserSub]);

    await dispatchEventChange(
      { uid: 'event-uid-4', title: 'Dentist', operation: 'create' },
      /* actorUserId */ 1,
    );

    expect(vi.mocked(dispatchPush)).toHaveBeenCalled();
    const calledWith = vi.mocked(dispatchPush).mock.calls[0][1];
    expect(calledWith.title).toContain('Lucas');
  });

  it('falls back to "A family member" when actor row is missing (IN-01)', async () => {
    const { db } = await import('../../src/db/client.js');
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    const { dispatchEventChange } = await import('../../src/lib/eventChangeDispatcher.js');

    const otherUserSub = {
      id: 2,
      userId: 2,
      endpoint: 'https://push.example.com/sub/2',
      p256dh: 'x',
      auth: 'y',
    };
    setupDbMock(vi.mocked(db), null, [otherUserSub]); // actor row absent → empty array

    await dispatchEventChange(
      { uid: 'event-uid-5', title: 'Soccer', operation: 'create' },
      /* actorUserId */ 99, // non-existent user
    );

    expect(vi.mocked(dispatchPush)).toHaveBeenCalled();
    const calledWith = vi.mocked(dispatchPush).mock.calls[0][1];
    expect(calledWith.title).toContain('A family member');
  });
});
