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

/**
 * Guards the JSON shape of POST /api/v1/auth/register against drift between fe0 and be0.
 * Full stack checks: be0/tests/test_registration_stack_alignment.py (REGISTRATION_STACK_TEST=1).
 */
describe('authService.register request body', () => {
  beforeEach(() => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue(
        new Response(
          JSON.stringify({
            emailVerificationRequired: true,
            message: 'Kiểm tra email.',
            email: 'user@ump.edu.vn',
            user: {
              id: '00000000-0000-4000-8000-000000000001',
              email: 'user@ump.edu.vn',
              name: 'Tester',
              roles: ['viewer'],
              emailVerified: false,
              staffProfile: {},
            },
          }),
          { status: 200 },
        ),
      ),
    );
  });

  afterEach(() => {
    vi.unstubAllGlobals();
  });

  it('JSON body keys match backend RegisterBody / Python _fe0_style_register_json', async () => {
    const { authService } = await import('./auth-service');

    await authService.register({
      fullName: 'Nguyễn Văn A',
      email: 'user@ump.edu.vn',
      password: 'Secret1!',
      passwordConfirm: 'Secret1!',
      employeeId: 'CB-TEST01',
      academicTitleCode: 'master',
      unitNameFreetext: 'Khoa thử',
      jobTitle: 'Cán bộ',
    });

    const init = vi.mocked(fetch).mock.calls[0]?.[1] as RequestInit | undefined;
    expect(init?.method).toBe('POST');
    const raw = init?.body;
    expect(typeof raw).toBe('string');
    const body = JSON.parse(raw as string) as Record<string, unknown>;

    expect(Object.keys(body).sort()).toEqual(
      [
        'academicTitleCode',
        'email',
        'employeeId',
        'fullName',
        'jobTitle',
        'password',
        'passwordConfirm',
        'unitNameFreetext',
      ].sort(),
    );
    expect(body.email).toBe('user@ump.edu.vn');
    expect(body.fullName).toBe('Nguyễn Văn A');
    expect(body.password).toBe('Secret1!');
    expect(body.passwordConfirm).toBe('Secret1!');
  });
});
