import { beforeEach, describe, expect, it, vi } from 'vitest';
import { subscribeToPush } from './notifications.js';

describe('subscribeToPush', () => {
  beforeEach(() => {
    vi.restoreAllMocks();
    localStorage.clear();
  });

  it('sends the subscription request with credentials so the session is preserved', async () => {
    const fetchMock = vi.fn()
      .mockResolvedValueOnce({ ok: true, json: async () => ({ publicKey: 'test-public-key' }) })
      .mockResolvedValueOnce({ ok: true, text: async () => '' });

    vi.stubGlobal('fetch', fetchMock);

    Object.defineProperty(window, 'isSecureContext', {
      configurable: true,
      value: true,
    });

    Object.defineProperty(window, 'PushManager', {
      configurable: true,
      value: class PushManager {},
    });

    Object.defineProperty(window, 'Notification', {
      configurable: true,
      value: { permission: 'granted' },
    });

    Object.defineProperty(navigator, 'serviceWorker', {
      configurable: true,
      value: {
        ready: Promise.resolve({
          pushManager: {
            getSubscription: vi.fn().mockResolvedValue(null),
            subscribe: vi.fn().mockResolvedValue({ endpoint: 'https://example.test/push' }),
          },
        }),
      },
    });

    await subscribeToPush('123456', 'Paracetamol');

    expect(fetchMock).toHaveBeenCalledTimes(2);
    expect(fetchMock.mock.calls[1][1]).toMatchObject({
      method: 'POST',
      credentials: 'include',
    });
  });
});
