/**
 * RED scaffold — pushDispatcher (Plan 05-02 turns this GREEN).
 *
 * Asserts that dispatchPush:
 *   - Deletes the push_subscriptions row when the push service returns 410 (Gone)
 *   - Deletes the push_subscriptions row when the push service returns 404 (Not Found)
 *   - Does NOT delete the row on 201 (success)
 *   - Does NOT delete the row on transient 5xx errors
 *
 * These tests fail now because pushDispatcher.ts does not yet exist.
 * Run: pnpm --filter @familysync/api exec vitest run tests/lib/pushDispatcher.test.ts
 */

import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { PushSubscription } from '../../src/lib/pushDispatcher.js';

// Mock web-push so no real network calls occur
vi.mock('web-push', () => ({
  default: {
    sendNotification: vi.fn(),
    setVapidDetails: vi.fn(),
  },
}));

// Mock the DB module so we can assert on deletes without a real database
vi.mock('../../src/db/client.js', () => ({
  db: {
    delete: vi.fn().mockReturnValue({
      where: vi.fn().mockResolvedValue(undefined),
    }),
  },
}));

const FAKE_SUB: PushSubscription = {
  id: 1,
  userId: 42,
  endpoint: 'https://push.example.com/sub/abc',
  p256dh: 'fake_p256dh',
  auth: 'fake_auth',
};

describe('pushDispatcher — 410/404 subscription pruning', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('deletes the subscription row when the push service returns 410 (Gone)', async () => {
    const webpush = (await import('web-push')).default;
    const { db } = await import('../../src/db/client.js');
    vi.mocked(webpush.sendNotification).mockRejectedValueOnce(
      Object.assign(new Error('Gone'), { statusCode: 410 }),
    );

    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    await dispatchPush(FAKE_SUB, { title: 'Test', body: 'Hello' });

    expect(vi.mocked(db.delete)).toHaveBeenCalled();
  });

  it('deletes the subscription row when the push service returns 404 (Not Found)', async () => {
    const webpush = (await import('web-push')).default;
    const { db } = await import('../../src/db/client.js');
    vi.mocked(webpush.sendNotification).mockRejectedValueOnce(
      Object.assign(new Error('Not Found'), { statusCode: 404 }),
    );

    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    await dispatchPush(FAKE_SUB, { title: 'Test', body: 'Hello' });

    expect(vi.mocked(db.delete)).toHaveBeenCalled();
  });

  it('does NOT delete the row on 201 success', async () => {
    const webpush = (await import('web-push')).default;
    const { db } = await import('../../src/db/client.js');
    vi.mocked(webpush.sendNotification).mockResolvedValueOnce({
      statusCode: 201,
      body: '',
      headers: {},
    });

    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    await dispatchPush(FAKE_SUB, { title: 'Test', body: 'Hello' });

    expect(vi.mocked(db.delete)).not.toHaveBeenCalled();
  });

  it('does NOT delete the row on transient 5xx error', async () => {
    const webpush = (await import('web-push')).default;
    const { db } = await import('../../src/db/client.js');
    vi.mocked(webpush.sendNotification).mockRejectedValueOnce(
      Object.assign(new Error('Service Unavailable'), { statusCode: 503 }),
    );

    const { dispatchPush } = await import('../../src/lib/pushDispatcher.js');
    await dispatchPush(FAKE_SUB, { title: 'Test', body: 'Hello' });

    expect(vi.mocked(db.delete)).not.toHaveBeenCalled();
  });
});
