/**
 * reminderScheduler tests.
 *
 * Asserts that the reminder scan:
 *   - Selects ONLY shared (isShared=true) AND timed (allDay=false) events
 *     in the [now+14min, now+16min] window (D-05/D-06/D-07)
 *   - Does NOT dispatch reminders for all-day events (D-07)
 *   - Does NOT dispatch reminders for non-shared (personal) events (D-05)
 *   - Does NOT dispatch the same (eventUid, minuteBucket) twice within the same minute
 *   - CR-01: sentReminders Set is pruned after each scan (no unbounded growth)
 *   - WR-01: sentReminders.add() is called AFTER dispatch (at-least-once delivery)
 *
 * Run: pnpm --filter @familysync/api exec vitest run tests/broker/reminderScheduler.test.ts
 */

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

// Mock the DB so we can control what events are returned
vi.mock('../../src/db/client.js', () => ({
  db: {
    select: vi.fn(),
  },
}))

// Mock pushDispatcher so no real push occurs
vi.mock('../../src/lib/pushDispatcher.js', () => ({
  dispatchPush: vi.fn().mockResolvedValue(undefined),
}))

describe('reminderScheduler — shared+timed event filtering (D-05/D-06/D-07)', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    vi.resetModules()
  })

  afterEach(() => {
    vi.useRealTimers()
    vi.clearAllMocks()
  })

  it('does not dispatch reminders for all-day events (D-07)', async () => {
    const now = new Date('2026-06-15T10:00:00Z')
    vi.setSystemTime(now)

    const { db } = await import('../../src/db/client.js')
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js')
    const { runReminderCheck } = await import('../../src/broker/reminderScheduler.js')

    // Simulate: query returns an all-day event (allDay=true)
    // The scheduler should have filtered this out in SQL — return empty results
    vi.mocked(db.select).mockReturnValue({
      from: vi.fn().mockReturnValue({
        innerJoin: vi.fn().mockReturnValue({
          innerJoin: vi.fn().mockReturnValue({
            where: vi.fn().mockResolvedValue([]),
          }),
        }),
      }),
    } as never)

    await runReminderCheck()

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

  it('does not dispatch reminders for non-shared (personal) calendar events (D-05)', async () => {
    const now = new Date('2026-06-15T10:00:00Z')
    vi.setSystemTime(now)

    const { db } = await import('../../src/db/client.js')
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js')
    const { runReminderCheck } = await import('../../src/broker/reminderScheduler.js')

    // SQL WHERE clause must include isShared=true; no personal events returned
    vi.mocked(db.select).mockReturnValue({
      from: vi.fn().mockReturnValue({
        innerJoin: vi.fn().mockReturnValue({
          innerJoin: vi.fn().mockReturnValue({
            where: vi.fn().mockResolvedValue([]),
          }),
        }),
      }),
    } as never)

    await runReminderCheck()

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

  it('does not dispatch the same (eventUid, minuteBucket) pair twice within the same run', async () => {
    const now = new Date('2026-06-15T10:00:00Z')
    vi.setSystemTime(now)

    const { db } = await import('../../src/db/client.js')
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js')
    const { runReminderCheck } = await import('../../src/broker/reminderScheduler.js')

    const sharedTimedEvent = {
      uid: 'event-uid-123',
      title: 'Team standup',
      dtstartUtc: new Date('2026-06-15T10:15:00Z'), // 15 min from now
      allDay: false,
      isShared: true,
      subscriptions: [],
    }

    vi.mocked(db.select)
      .mockReturnValueOnce({
        from: vi.fn().mockReturnValue({
          innerJoin: vi.fn().mockReturnValue({
            innerJoin: vi.fn().mockReturnValue({
              where: vi.fn().mockResolvedValue([sharedTimedEvent]),
            }),
          }),
        }),
      } as never)
      .mockReturnValue({
        from: vi.fn().mockReturnValue({
          innerJoin: vi.fn().mockReturnValue({
            innerJoin: vi.fn().mockReturnValue({
              where: vi.fn().mockResolvedValue([sharedTimedEvent]),
            }),
          }),
        }),
      } as never)

    // First run — should dispatch
    await runReminderCheck()
    const firstCallCount = vi.mocked(dispatchPush).mock.calls.length

    // Second run in the same minute — same (uid, minuteBucket) — should NOT dispatch again
    await runReminderCheck()
    const secondCallCount = vi.mocked(dispatchPush).mock.calls.length

    expect(secondCallCount).toBe(firstCallCount)
  })
})

describe('reminderScheduler — CR-01: sentReminders Set pruning', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    vi.resetModules()
  })

  afterEach(() => {
    vi.useRealTimers()
    vi.clearAllMocks()
  })

  it('does not re-dispatch an event in the next minute bucket (pruned entry allows new minute)', async () => {
    const { db } = await import('../../src/db/client.js')
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js')
    const { runReminderCheck } = await import('../../src/broker/reminderScheduler.js')

    // Event with one subscriber
    const sub = { id: 1, userId: 1, endpoint: 'https://push.example.com/1', p256dh: 'k', auth: 'a' }
    const eventRow = {
      uid: 'prune-test-uid',
      title: 'Prune test event',
      dtstartUtc: new Date('2026-06-15T10:15:00Z'),
      allDay: false,
      isShared: true,
      subId: sub.id,
      subUserId: sub.userId,
      subEndpoint: sub.endpoint,
      subP256dh: sub.p256dh,
      subAuth: sub.auth,
    }

    function makeSelectMock() {
      return {
        from: vi.fn().mockReturnValue({
          innerJoin: vi.fn().mockReturnValue({
            innerJoin: vi.fn().mockReturnValue({
              where: vi.fn().mockResolvedValue([eventRow]),
            }),
          }),
        }),
      } as never
    }

    // Minute bucket 0
    const t0 = new Date('2026-06-15T10:00:00Z')
    vi.setSystemTime(t0)
    vi.mocked(db.select).mockReturnValue(makeSelectMock())
    await runReminderCheck(t0)
    const dispatchCountAfterMinute0 = vi.mocked(dispatchPush).mock.calls.length
    expect(dispatchCountAfterMinute0).toBe(1) // fired once

    // Same minute — dedup must prevent re-fire
    vi.mocked(db.select).mockReturnValue(makeSelectMock())
    await runReminderCheck(t0)
    expect(vi.mocked(dispatchPush).mock.calls.length).toBe(1) // still 1

    // Advance to minute bucket 2 (bucket 0 entry is now stale: bucket < currentBucket - 1)
    const t2 = new Date('2026-06-15T10:02:00Z')
    vi.setSystemTime(t2)
    vi.mocked(db.select).mockReturnValue(makeSelectMock())
    await runReminderCheck(t2)
    // The stale bucket-0 entry was pruned after the bucket-1 scan.
    // A new dispatch fires for the same event in bucket-2.
    expect(vi.mocked(dispatchPush).mock.calls.length).toBe(2)
  })
})

describe('reminderScheduler — WR-01: mark-sent after dispatch', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    vi.resetModules()
  })

  afterEach(() => {
    vi.useRealTimers()
    vi.clearAllMocks()
  })

  it('does not re-dispatch in the same minute bucket after a successful dispatch', async () => {
    // WR-01: sentReminders.add(key) is called AFTER the fan-out loop completes.
    // After a successful dispatch the key is added, and a second run in the same
    // bucket must not re-fire.
    const { db } = await import('../../src/db/client.js')
    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js')
    const { runReminderCheck } = await import('../../src/broker/reminderScheduler.js')

    const now = new Date('2026-06-15T10:00:00Z')
    vi.setSystemTime(now)

    const sub = { id: 1, userId: 1, endpoint: 'https://push.example.com/1', p256dh: 'k', auth: 'a' }
    const eventRow = {
      uid: 'wr01-dedup-uid',
      title: 'WR-01 dedup event',
      dtstartUtc: new Date('2026-06-15T10:15:00Z'),
      allDay: false,
      isShared: true,
      subId: sub.id,
      subUserId: sub.userId,
      subEndpoint: sub.endpoint,
      subP256dh: sub.p256dh,
      subAuth: sub.auth,
    }

    function makeSelectMock() {
      return {
        from: vi.fn().mockReturnValue({
          innerJoin: vi.fn().mockReturnValue({
            innerJoin: vi.fn().mockReturnValue({
              where: vi.fn().mockResolvedValue([eventRow]),
            }),
          }),
        }),
      } as never
    }

    vi.mocked(dispatchPush).mockResolvedValue(undefined)

    // First run — dispatch succeeds; key is added after the loop
    vi.mocked(db.select).mockReturnValue(makeSelectMock())
    await runReminderCheck(now)
    expect(vi.mocked(dispatchPush).mock.calls.length).toBe(1) // dispatched once

    // Second run in the same bucket — key exists; should NOT re-dispatch
    vi.mocked(db.select).mockReturnValue(makeSelectMock())
    await runReminderCheck(now)
    expect(vi.mocked(dispatchPush).mock.calls.length).toBe(1) // still 1 — deduped
  })
})
