import axios from 'axios';
import { generateQr, getQr } from '../qr';
import { resetMemoryStorage } from '../storage/memory';

jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

const FAKE_IMAGE = Buffer.from('fake-png-data');

beforeEach(() => {
    resetMemoryStorage();
    jest.resetAllMocks();
    mockedAxios.get = jest.fn().mockResolvedValue({ data: FAKE_IMAGE });
});

test('generateQr zavolá Paylibo API se správnými parametry', async () => {
    await generateQr('jannovak', '19-2000145399/0800', 'Jan Novák', 149, 'Pizza Margherita', 'test-uuid-1');
    expect(mockedAxios.get).toHaveBeenCalledTimes(1);
    const [url, config] = (mockedAxios.get as jest.Mock).mock.calls[0];
    expect(url).toContain('paylibo.com');
    expect(config.params.amount).toBe(149);
    expect(config.params.iban).toBeDefined();
});

test('generateQr uloží base64 obrázek do storage', async () => {
    await generateQr('jannovak', '19-2000145399/0800', 'Jan Novák', 149, 'Pizza', 'test-uuid-2');
    const img = await getQr('jannovak', 'test-uuid-2');
    expect(Buffer.isBuffer(img)).toBe(true);
    expect(img).toEqual(FAKE_IMAGE);
});

test('generateQr ořeže zprávu delší než 60 znaků', async () => {
    const dlouhaZprava = 'Pizza ' + 'x'.repeat(60);
    await generateQr('jannovak', '19-2000145399/0800', 'Jan Novák', 149, dlouhaZprava, 'test-uuid-3');
    const [, config] = (mockedAxios.get as jest.Mock).mock.calls[0];
    expect(config.params.message.length).toBeLessThanOrEqual(60);
});

test('generateQr odstraní hvězdičku ze zprávy', async () => {
    await generateQr('jannovak', '19-2000145399/0800', 'Jan Novák', 149, 'Pizza *Margherita*', 'test-uuid-4');
    const [, config] = (mockedAxios.get as jest.Mock).mock.calls[0];
    expect(config.params.message).not.toContain('*');
});

test('getQr hodí chybu pro neexistující ID', async () => {
    await expect(getQr('jannovak', 'neexistuje')).rejects.toThrow('nebyl nalezen');
});
