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

const { requireAuthMock, listPosteMock, createPosteMock } = vi.hoisted(() => ({
  requireAuthMock: vi.fn(),
  listPosteMock: vi.fn(),
  createPosteMock: vi.fn(),
}));

vi.mock('@/lib/requireAuth', () => ({
  requireAuth: requireAuthMock,
}));

vi.mock('@/services/reference-lookups.service', () => ({
  listPostes: listPosteMock,
  createPoste: createPosteMock,
}));

import { GET, POST } from '../../../../src/app/api/postes/route';

describe('Unit — /api/postes route', () => {
  beforeEach(() => {
    vi.resetAllMocks();
    requireAuthMock.mockReturnValue(null);
  });

  it('GET returns the paginated postelist', async () => {
    listPosteMock.mockResolvedValue([
      {
        id: 1,
        poste: 'posteautorisee',
        libposte: 'AA',
        date_creation: '2026-05-21T08:16:08.000Z',
      },
    ]);

    const res = await GET(new Request('http://localhost/api/postes'));

    expect(res.status).toBe(200);
    expect(listPosteMock).toHaveBeenCalledWith(20, 0);

    const body = await res.json();
    expect(body).toEqual({
      message: 'Postes retrieved successfully',
      items: [
        {
          id: 1,
          poste: 'posteautorisee',
          libposte: 'AA',
          date_creation: '2026-05-21T08:16:08.000Z',
        },
      ],
      count: 1,
    });
  });

  it('GET returns 400 for invalid query parameters', async () => {
    const res = await GET(new Request('http://localhost/apipostes?limit=abc'));

    expect(res.status).toBe(400);
    expect(listPosteMock).not.toHaveBeenCalled();

    const body = await res.json();
    expect(body.message).toBe('Invalid query parameters');
  });

  it('POST creates a Poste', async () => {
    createPosteMock.mockResolvedValue({
      id: 1,
      etablissement: "etb",
          pos: "pos",
          intitule:"TITRE",
          code_poste: "59763",
          description: "desc",
    });

    const res = await POST(
      new Request('http://localhost/apipostes', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
           etablissement: "etb",
          pos: "pos",
          intitule:"TITRE",
          code_poste: "59763",
          description: "desc",
        }),
      }),
    );

    expect(res.status).toBe(201);
    expect(createPosteMock).toHaveBeenCalledWith({
       etablissement: "etb",
          pos: "pos",
          intitule:"TITRE",
          code_poste: "59763",
          description: "desc",
    });

    const body = await res.json();
    expect(body).toEqual({
      message: 'Poste created successfully',
      poste: {
        id: 1,
         etablissement: "etb",
          pos: "pos",
          intitule:"TITRE",
          code_poste: "59763",
          description: "desc",
      },
    });
  });

  it('POST returns 400 for invalid JSON', async () => {
    const res = await POST(
      new Request('http://localhost/apipostes', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: '{"Poste": "posteautorisee"',
      }),
    );

    expect(res.status).toBe(400);
    expect(createPosteMock).not.toHaveBeenCalled();

    const body = await res.json();
    expect(body.message).toBe('Invalid JSON body');
  });

  it('POST returns 400 for invalid body', async () => {
    const res = await POST(
      new Request('http://localhost/apipostes', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ libposte: 'Missing Poste' }),
      }),
    );

    expect(res.status).toBe(400);
    expect(createPosteMock).not.toHaveBeenCalled();

    const body = await res.json();
    expect(body.message).toBe('Invalid body parameters');
  });
  it('Post returns auth error when request is unauthorized', async () => {
      requireAuthMock.mockReturnValue(new Response('Unauthorized', { status: 401 }));
  
      const res = await POST(new Request('http://localhost/api/type-poste'));
  
      expect(res.status).toBe(401);
      expect(createPosteMock).not.toHaveBeenCalled();
    });
});