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

// Detail page reflects the reader's personal progress: chapters at or before
// the last-read chapter are marked read, and a "N new since last read" badge
// counts chapters that have landed since.

const mangaId = 'a1111111-1111-1111-1111-111111111111';
const ch1 = 'c1111111-1111-1111-1111-111111111111';
const ch2 = 'c2222222-2222-2222-2222-222222222222';
const ch3 = 'c3333333-3333-3333-3333-333333333333';

// Oldest-first, as repo::chapter::list_for_manga returns them.
const chapters = [
    { id: ch1, manga_id: mangaId, number: 1, title: null, page_count: 8, created_at: '2026-01-01T00:00:00Z' },
    { id: ch2, manga_id: mangaId, number: 2, title: null, page_count: 10, created_at: '2026-02-01T00:00:00Z' },
    { id: ch3, manga_id: mangaId, number: 3, title: null, page_count: 10, created_at: '2026-03-01T00:00:00Z' }
];

async function mockDetail(
    page: Page,
    readProgress: {
        chapter_id: string;
        chapter_number: number;
        page: number;
        new_chapters_count: number;
    } | null
) {
    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: 200, contentType: 'application/json', body: JSON.stringify({ user: { id: 'u1', username: 'reader', created_at: '2026-01-01T00:00:00Z', is_admin: false } }) })
    );
    await page.route('**/api/v1/auth/me/preferences', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: '{}' })
    );
    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/mangas/${mangaId}/chapters*`, (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: chapters, page: { limit: 50, offset: 0, total: 3 } }) })
    );
    await page.route(`**/api/v1/mangas/${mangaId}/similar`, (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [] }) })
    );
    await page.route(`**/api/v1/me/read-progress/${mangaId}`, (r) =>
        r.fulfill({
            status: readProgress ? 200 : 404,
            contentType: 'application/json',
            body: readProgress ? JSON.stringify(readProgress) : JSON.stringify({ error: { code: 'not_found', message: 'no' } })
        })
    );
    // getManga — registered last so it wins over the chapters glob above.
    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('marks read chapters and counts new ones when mid-series', async ({ page }) => {
    // Backend reports 2 distinct new chapters (2 and 3) past chapter 1.
    await mockDetail(page, { chapter_id: ch1, chapter_number: 1, page: 1, new_chapters_count: 2 });
    await page.goto(`/manga/${mangaId}`);

    // Chapter 1 is read; 2 and 3 are not.
    await expect(page.getByTestId(`chapter-read-${ch1}`)).toBeVisible();
    await expect(page.getByTestId(`chapter-read-${ch2}`)).toHaveCount(0);
    await expect(page.getByTestId(`chapter-read-${ch3}`)).toHaveCount(0);

    // Two chapters landed since last read.
    await expect(page.getByTestId('new-chapters-summary')).toContainText('2 new');
});

test('no markers or new-badge when the manga was never opened', async ({ page }) => {
    await mockDetail(page, null);
    await page.goto(`/manga/${mangaId}`);

    await expect(page.getByTestId('chapter-list')).toBeVisible();
    await expect(page.getByTestId(`chapter-read-${ch1}`)).toHaveCount(0);
    await expect(page.getByTestId('new-chapters-summary')).toHaveCount(0);
});
