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

test.describe('Journey Management (History)', () => {
    test.beforeEach(async ({ page }) => {
        // Mock Auth
        await page.context().addCookies([{
            name: 'auth-token',
            value: 'authenticated',
            domain: 'localhost',
            path: '/',
            httpOnly: true,
            secure: false,
            sameSite: 'Lax'
        }]);
    });

    test('should save instance from chat -> view in history -> delete', async ({ page }) => {
        // 1. Setup Provider
        await page.goto('/settings');
        await page.getByRole('button', { name: 'Add New Provider' }).click();
        await page.fill('input[placeholder="My OpenAI Key"]', 'Test Provider');
        await page.fill('input[placeholder="https://api.openai.com/v1"]', 'https://api.example.com/v1');
        await page.fill('input[placeholder="gpt-4o"]', 'test-model');
        await page.fill('input[placeholder="sk-..."]', 'sk-test-key');
        await page.getByRole('button', { name: 'Save as New Provider' }).click();

        // Mock API
        await page.route('/api/llm', async route => {
            const body = route.request().postDataJSON();

            // Validation Check (hello)
            if (body.messages.length === 1 && body.messages[0].content === 'hello') {
                await route.fulfill({ json: { success: true, data: { text: 'Hello' } } });
                return;
            }

            // Teacher Response
            if (body.messages.some((m: any) => m.role === 'system' && m.content.includes('"Teacher"'))) {
                await route.fulfill({ json: { success: true, data: { text: 'Go on...' } } });
                return;
            }

            // Ghostwriter Response
            if (body.messages.some((m: any) => m.role === 'system' && m.content.includes('"Ghostwriter"'))) {
                await route.fulfill({
                    json: {
                        success: true, data: {
                            text: JSON.stringify({
                                title: "History Test Entry",
                                insight: "Persistence is key.",
                                lesson: "Always save your work."
                            })
                        }
                    }
                });
                return;
            }

            // Fallback
            await route.fulfill({ json: { success: true, data: { text: 'Fallback response' } } });
        });

        await expect(page.getByText('Go on...')).toBeVisible();
        await page.click('button:has-text("Summarize & Draft")');
        await expect(page.getByText('History Test Entry')).toBeVisible();
        await page.getByRole('button', { name: 'Keep It' }).click();

        // 3. Verify Redirection to History
        await expect(page).toHaveURL(/.*\/history/);

        // 4. Verify Entry in List
        await expect(page.getByText('History Test Entry')).toBeVisible();

        // 5. Delete Entry
        await page.getByText('History Test Entry').click();
        await page.getByRole('button', { name: 'Delete' }).click();
        await page.getByRole('button', { name: 'Confirm Delete' }).click(); // Assuming dialog

        await expect(page.getByText('History Test Entry')).toBeHidden();
    });
});
