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

const { requireAuthMock, listAbsenceMock, createAbsenceMock } = vi.hoisted(() => ({
    requireAuthMock: vi.fn(),
    listAbsenceMock: vi.fn(),
    createAbsenceMock: vi.fn(),
}));

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

vi.mock('@/server/absences.server', () => ({
    getAbsencesFeed: listAbsenceMock,
    createAbsenceFeed: createAbsenceMock,
}));

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

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

    it('GET returns the paginated absencelist', async () => {
        listAbsenceMock.mockResolvedValue({
            items: [
                {
                    id: 1,
                    absence: 'absenceautorisee',
                    libabsence: 'AA',
                    date_creation: '2026-05-21T08:16:08.000Z',
                },
            ],
            count: 1,
        });

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

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

        const body = await res.json();
        expect(body).toEqual({
            message: 'Absences retrieved successfully',
            items: [
                {
                    id: 1,
                    absence: 'absenceautorisee',
                    libabsence: '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/api/absences?limit=abc'));

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

        const body = await res.json();
        expect(body.message).toBe('Invalid query parameters');
    });
      it('GET returns auth error when request is unauthorized', async () => {
        requireAuthMock.mockReturnValue(new Response('Unauthorized', { status: 401 }));

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

        expect(res.status).toBe(401);
        expect(listAbsenceMock).not.toHaveBeenCalled();
    });
    it('POST creates a Absence', async () => {
        createAbsenceMock.mockResolvedValue({
            absence: {
                id: 1,
                id_salarie: 1,
                typeabsence: "Malade",
                idabsences: 1
            }
        });

        const res = await POST(
            new Request('http://localhost/api/absences', {
                method: 'POST',
                headers: { 'content-type': 'application/json' },
                body: JSON.stringify({
                    id_salarie: 1,
                    typeabsence: "Malade",
                    idabsences: 1
                }),
            }),
        );

        expect(res.status).toBe(201);
        expect(createAbsenceMock).toHaveBeenCalledWith({
            id_salarie: 1,
            typeabsence: "Malade",
            idabsences: 1
        });

        const body = await res.json();
        expect(body).toEqual({
            message: 'Absence created successfully',
            absence: {
                id: 1,
                id_salarie: 1,
                typeabsence: "Malade",
                idabsences: 1
            },
        });
    });

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

        expect(res.status).toBe(400);
        expect(createAbsenceMock).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/api/absences', {
                method: 'POST',
                headers: { 'content-type': 'application/json' },
                body: JSON.stringify({ libabsence: 'Missing Absence' }),
            }),
        );

        expect(res.status).toBe(400);
        expect(createAbsenceMock).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/absences'));

        expect(res.status).toBe(401);
        expect(createAbsenceMock).not.toHaveBeenCalled();
    });
});