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

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

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

vi.mock('../../../../src/server/sanction.server', () => ({
    getSanctionsByEmployeCosFeed: getSanctionsByEmployeCosFeedMock
}));

import { GET } from '../../../../src/app/api/employes/[cos]/disciplinaires/route';

const makeCtx = <T extends (...args: any[]) => any>(fn: T, params: Record<string, string>) => ({ params: Promise.resolve(params) } as unknown as Parameters<T>[1]);

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

    it('GET returns 200 when sanction exists', async () => {
            getSanctionsByEmployeCosFeedMock.mockResolvedValue({
                    employe: { COS: 123 },
                    items: [
                        { id: 1, id_salarie: 123 },
                        { id: 2, id_salarie: 123 },
                    ],
                    count: 2,
                });

            const res = await GET(new Request('http://localhost/api/employes/123/sanctions'), makeCtx(GET, { cos: '123' }));

            expect(res.status).toBe(200);
            const body = await res.json();
            expect(body).toEqual({
                message: 'Sanctions by employe retrieved successfully',
                items: [
                    { id: 1, id_salarie: 123 },
                    { id: 2, id_salarie: 123 },
                ],
                count: 2,
            });
    });

    it('GET returns 400 when id param is invalid', async () => {
        const res = await GET(new Request('http://localhost/api/employes/abc/sanctions'), makeCtx(GET, { cos: 'abc' }));

        expect(res.status).toBe(400);
        const body = await res.json();
        expect(body.message).toBe('Invalid ID parameter');
    });
    it('GET returns auth error when request is unauthorized', async () => {
        // simulate requireAuth returning an HTTP 401 Response
        requireAuthMock.mockReturnValue(new Response('Unauthorized', { status: 401 }));

        const res = await GET(new Request('http://localhost/api/employes/1/sanctions'), makeCtx(GET, { cos: '1' }));

        expect(res.status).toBe(401);
        expect(getSanctionsByEmployeCosFeedMock).not.toHaveBeenCalled();
    });
    it('GET returns 404 when not found', async () => {
        getSanctionsByEmployeCosFeedMock.mockResolvedValue({ employe: null });

        const res = await GET(new Request('http://localhost/api/employes/999/disciplinaires'), makeCtx(GET, { cos: '999' }));

        expect(res.status).toBe(404);
        const body = await res.json();
        expect(body.message).toBe('Employe not found');
    });


});
