import { test, expect, type Page } from './fixtures';

// The detail page's Continue/Read CTA is the highest-intent link to the
// heaviest route in the app. It should be programmatically preloaded so the
// reader's data (and first page images) are warm before the tap — proven here
// by the reader-only chapter-pages endpoint being requested on the detail page
// without any click.

const mangaId = 'c1111111-1111-1111-1111-111111111111';
const chId = 'cc111111-1111-1111-1111-111111111111';

async function mockDetailAndReader(page: Page) {
    await page.route('**/api/v1/auth/config', (r) =>
        r.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ self_register_enabled: true, private_mode: false })
        })
    );
    await page.route('**/api/v1/auth/me', (r) =>
        r.fulfill({ status: 401, contentType: 'application/json', body: '{"error":{"code":"x","message":"x"}}' })
    );
    await page.route('**/api/v1/auth/me/preferences', (r) =>
        r.fulfill({ status: 401, contentType: 'application/json', body: '{"error":{"code":"x","message":"x"}}' })
    );
    await page.route('**/api/v1/me/bookmarks*', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [], page: { limit: 50, offset: 0, total: 0 } }) })
    );
    await page.route(`**/api/v1/me/read-progress/${mangaId}`, (r) =>
        r.fulfill({ status: 404, contentType: 'application/json', body: '{"error":{"code":"x","message":"x"}}' })
    );
    await page.route(`**/api/v1/me/reactions/${mangaId}`, (r) =>
        r.fulfill({ status: 404, contentType: 'application/json', body: '{"error":{"code":"x","message":"x"}}' })
    );
    await page.route(`**/api/v1/mangas/${mangaId}/similar`, (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [] }) })
    );
    // Chapter list (detail + reader both use this).
    const chapters = [
        { id: chId, manga_id: mangaId, number: 1, title: null, page_count: 3, created_at: '2026-01-01T00:00:00Z' }
    ];
    await page.route(`**/api/v1/mangas/${mangaId}/chapters*`, (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: chapters, page: { limit: 200, offset: 0, total: 1 } }) })
    );
    // Single-chapter fetch (reader only).
    await page.route(`**/api/v1/mangas/${mangaId}/chapters/${chId}`, (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(chapters[0]) })
    );
    await page.route(`**/api/v1/mangas/${mangaId}`, (r) =>
        r.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({
                id: mangaId, title: 'Berserk', status: 'ongoing', alt_titles: [], description: null,
                cover_image_path: null, created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
                authors: [], genres: [], tags: [], content_warnings: [], chapter_storage_bytes: 0
            })
        })
    );
}

test('programmatically preloads the reader from the detail CTA', async ({ page }) => {
    await mockDetailAndReader(page);

    // The chapter-pages endpoint is fetched only by the reader's load.
    let pagesRequested: () => void = () => {};
    const pagesHit = new Promise<void>((resolve) => {
        pagesRequested = resolve;
    });
    await page.route(`**/api/v1/mangas/${mangaId}/chapters/${chId}/pages`, (route) => {
        pagesRequested();
        return route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ pages: [{ id: 'p1', number: 1, image_path: 'x', width: null, height: null }] })
        });
    });

    await page.goto(`/manga/${mangaId}`);
    // Detail rendered (so ctaTarget is resolved to the first chapter).
    await expect(page.getByTestId('manga-title')).toHaveText('Berserk');

    // Preload fires the reader load (hence the pages endpoint) without a click.
    await expect(pagesHit).resolves.toBeUndefined();
});
