import { afterEach, describe, expect, it, vi } from 'vitest';
import { AlqoveClient } from '../../client';
import { createSchedulingEndpoints } from '../scheduling';

afterEach(() => vi.unstubAllGlobals());
describe('scheduling HTTP contract', () => {
  it('sends explicit copy intent, UTC shift bodies, opaque revisions and settings', async () => {
    const fetcher = vi.fn().mockImplementation(async () => new Response(JSON.stringify({ data: {} })));
    vi.stubGlobal('fetch', fetcher);
    const api = createSchedulingEndpoints(new AlqoveClient({ baseUrl: 'https://api.test' }));
    const input = { store_membership_id: null, position_id: null, starts_at: '2026-09-07T16:00:00Z', ends_at: '2026-09-08T00:00:00Z', notes: null };
    const revision = '2026-09-06T12:13:14.123456Z';
    await api.createShift('s1', input);
    await api.updateShift('s1', 'shift1', { ...input, revision });
    await api.deleteShift('s1', 'shift1', revision);
    await api.copyWeek('s1', { source_week_start: '2026-09-07', target_week_start: '2026-09-14', preview: true });
    await api.copyWeek('s1', { source_week_start: '2026-09-07', target_week_start: '2026-09-14', preview: false });
    await api.publish('s1', '2026-09-07');
    await api.settings('s1');
    await api.updateSettings('s1', { timezone: 'America/Chicago' });
    expect(fetcher.mock.calls.map(([url, opts]) => [url.replace('https://api.test/v1/stores/s1/', ''), opts.method, opts.body ? JSON.parse(opts.body) : undefined])).toEqual([
      ['schedule/shifts', 'POST', input], ['schedule/shifts/shift1', 'PATCH', { ...input, revision }],
      ['schedule/shifts/shift1', 'DELETE', { revision }],
      ['schedule/copy-week', 'POST', { source_week_start: '2026-09-07', target_week_start: '2026-09-14', preview: true }],
      ['schedule/copy-week', 'POST', { source_week_start: '2026-09-07', target_week_start: '2026-09-14', preview: false }],
      ['schedule/publish', 'POST', { week_start: '2026-09-07' }], ['schedule/settings', 'GET', undefined],
      ['schedule/settings', 'PATCH', { timezone: 'America/Chicago' }],
    ]);
  });
  it('reads store scoped week and own schedule without a supplied member id', async () => {
    const fetcher = vi.fn().mockImplementation(async () => new Response(JSON.stringify({ data: { shifts: [] } })));
    vi.stubGlobal('fetch', fetcher);
    const api = createSchedulingEndpoints(new AlqoveClient({ baseUrl: 'https://api.test' }));
    await api.week('store-1', '2026-09-07');
    await api.myWeek('store-1', '2026-09-07');
    expect(fetcher.mock.calls.map(([url]) => url)).toEqual([
      'https://api.test/v1/stores/store-1/schedule/week?week_start=2026-09-07',
      'https://api.test/v1/stores/store-1/my/schedule?week_start=2026-09-07',
    ]);
  });
});
