import { describe, test, expect, vi, beforeEach } from 'vitest';
import { Client } from '@vulog/aima-client';
import { randomUUID } from 'crypto';
import { getInvoicePdf } from './getInvoicePdf';

describe('getInvoicePdf', () => {
    const getMock = vi.fn();
    const client = {
        get: getMock,
        clientOptions: {
            fleetId: 'FLEET_ID',
        },
    } as unknown as Client;

    beforeEach(() => {
        getMock.mockReset();
    });

    test('throws Invalid args when invoiceId is not a valid UUID', async () => {
        await expect(getInvoicePdf(client, 'not-a-uuid')).rejects.toThrow(TypeError);
        await expect(getInvoicePdf(client, 'not-a-uuid')).rejects.toMatchObject({
            message: 'Invalid args',
        });
        expect(getMock).not.toHaveBeenCalled();
    });

    test('throws Invalid args when invoiceId is empty', async () => {
        await expect(getInvoicePdf(client, '')).rejects.toThrow(TypeError);
        expect(getMock).not.toHaveBeenCalled();
    });

    test('calls GET with correct URL and responseType arraybuffer, returns ArrayBuffer when data has length', async () => {
        const invoiceId = randomUUID();
        const pdfBuffer = new ArrayBuffer(1024);
        getMock.mockResolvedValueOnce({ data: pdfBuffer });

        const result = await getInvoicePdf(client, invoiceId);

        expect(getMock).toHaveBeenCalledTimes(1);
        expect(getMock).toHaveBeenCalledWith(
            `/boapi/proxy/billing/fleets/FLEET_ID/invoices/${invoiceId}/pdf`,
            { responseType: 'arraybuffer' }
        );
        expect(result).toBe(pdfBuffer);
        expect(result).toBeInstanceOf(ArrayBuffer);
        expect((result as ArrayBuffer).byteLength).toBe(1024);
    });

    test('returns null when response data is empty or zero length', async () => {
        const invoiceId = randomUUID();
        getMock.mockResolvedValueOnce({ data: new ArrayBuffer(0) });

        const result = await getInvoicePdf(client, invoiceId);

        expect(result).toBeNull();
    });
});
