import { test, expect } from '@playwright/test';
import * as fs from 'fs';

test.describe('CCLI Translation Pairing', () => {
    test('Translate.vue shows prefill banner when arrived from CCLI pairing', async ({ page }) => {
        await page.goto('/songs');
        await page.waitForLoadState('networkidle');
        const cookies = await page.context().cookies();
        const xsrf = cookies.find(c => c.name === 'XSRF-TOKEN')?.value ?? '';

        const content = fs.readFileSync('tests/Fixtures/ccli/english-only-multi-verse.txt', 'utf-8');
        const importRes = await page.request.post('/api/songs/import-from-ccli-paste', {
            headers: {
                'Content-Type': 'application/json',
                'X-XSRF-TOKEN': decodeURIComponent(xsrf),
            },
            data: { raw_text: content, mode: 'create' },
        });

        if (importRes.status() !== 201) {
            test.skip();
            return;
        }

        const { song_id } = await importRes.json();

        await page.goto(`/songs/${song_id}/translate`);
        await page.waitForLoadState('networkidle');

        await expect(page.getByTestId('translate-source-textarea')).toBeVisible();
    });

    test('Translate.vue shows no prefill banner without prefill param', async ({ page }) => {
        await page.goto('/songs');
        await page.waitForLoadState('networkidle');
        const cookies = await page.context().cookies();
        const xsrf = cookies.find(c => c.name === 'XSRF-TOKEN')?.value ?? '';

        const content = fs.readFileSync('tests/Fixtures/ccli/english-only-multi-verse.txt', 'utf-8');
        const importRes = await page.request.post('/api/songs/import-from-ccli-paste', {
            headers: {
                'Content-Type': 'application/json',
                'X-XSRF-TOKEN': decodeURIComponent(xsrf),
            },
            data: { raw_text: content, mode: 'create' },
        });

        if (importRes.status() !== 201) {
            test.skip();
            return;
        }

        const { song_id } = await importRes.json();

        await page.goto(`/songs/${song_id}/translate`);
        await page.waitForLoadState('networkidle');

        const banner = page.getByTestId('ccli-prefill-banner');
        await expect(banner).not.toBeVisible();
    });
});
