import { describe, it, expect, vi } from 'vitest';
import { WebPushDelivery } from './web-push.delivery';

const sub = { endpoint: 'https://push/x', p256dh: 'k', auth: 'a' };
const payload = { title: 'Bob', body: 'hi', data: { threadId: 'T1' } };
const vapid = { publicKey: 'p', privateKey: 'k', subject: 'mailto:x' };

describe('WebPushDelivery', () => {
  it('returns "sent" on success', async () => {
    const send = vi.fn().mockResolvedValue({ statusCode: 201 });
    const d = new WebPushDelivery(vapid, send as never);
    expect(await d.deliver(sub, payload)).toBe('sent');
    expect(send).toHaveBeenCalledOnce();
  });

  it('returns "gone" on 404/410 so the caller prunes', async () => {
    const d410 = new WebPushDelivery(vapid, vi.fn().mockRejectedValue({ statusCode: 410 }) as never);
    expect(await d410.deliver(sub, payload)).toBe('gone');
    const d404 = new WebPushDelivery(vapid, vi.fn().mockRejectedValue({ statusCode: 404 }) as never);
    expect(await d404.deliver(sub, payload)).toBe('gone');
  });

  it('returns "failed" on other errors', async () => {
    const d = new WebPushDelivery(vapid, vi.fn().mockRejectedValue({ statusCode: 500 }) as never);
    expect(await d.deliver(sub, payload)).toBe('failed');
  });

  it('is disabled (returns "failed", never calls send) without VAPID keys', async () => {
    const send = vi.fn();
    const d = new WebPushDelivery(undefined, send as never);
    expect(await d.deliver(sub, payload)).toBe('failed');
    expect(send).not.toHaveBeenCalled();
  });
});
