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

const mangaId = '22222222-2222-2222-2222-222222222222';
const userFixture = {
    id: 'u1',
    username: 'alice',
    created_at: '2026-01-01T00:00:00Z'
};
// Faithful `MangaDetail` (GET /v1/mangas/:id). The detail page reads
// authors/genres/tags/alt_titles/content_warnings during render, so these
// must be present or the component throws before painting.
const mangaFixture = {
    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: [{ id: 'a2222222-2222-2222-2222-222222222222', name: 'Kentaro Miura' }],
    genres: [],
    tags: [],
    content_warnings: [],
    chapter_storage_bytes: 0
};
const bookmarkFixture = {
    id: 'b1',
    user_id: 'u1',
    manga_id: mangaId,
    chapter_id: null,
    page: null,
    created_at: '2026-01-01T00:00:00Z'
};
// /me/bookmarks responses are enriched (`BookmarkSummary` on the wire),
// while POST /bookmarks returns the bare `Bookmark`. The mock layer
// returns the bare fixture on POST and the enriched one in the list.
const enrichedBookmarkFixture = {
    ...bookmarkFixture,
    manga_title: 'Berserk',
    manga_cover_image_path: null,
    chapter_number: null
};

async function setupAuthenticatedBookmarkFlow(page: Page) {
    let bookmarks: typeof enrichedBookmarkFixture[] = [];

    await page.route('**/api/v1/auth/me', (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ user: userFixture })
        })
    );
    await page.route(`**/api/v1/mangas/${mangaId}`, (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify(mangaFixture)
        })
    );
    await page.route(`**/api/v1/mangas/${mangaId}/chapters?*`, (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ items: [], page: { limit: 50, offset: 0, total: null } })
        })
    );
    await page.route(`**/api/v1/mangas/${mangaId}/chapters`, (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ items: [], page: { limit: 50, offset: 0, total: null } })
        })
    );
    await page.route('**/api/v1/me/bookmarks*', (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({
                items: bookmarks,
                page: { limit: 50, offset: 0, total: null }
            })
        })
    );
    // Authed but no saved position (404 → null) + empty recommendations —
    // both fetched by the manga-detail load's Promise.all.
    await page.route(`**/api/v1/me/read-progress/${mangaId}`, (route) =>
        route.fulfill({
            status: 404,
            contentType: 'application/json',
            body: JSON.stringify({ error: { code: 'not_found', message: 'no progress' } })
        })
    );
    await page.route(`**/api/v1/mangas/${mangaId}/similar`, (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ items: [] })
        })
    );
    await page.route('**/api/v1/bookmarks', (route) => {
        if (route.request().method() === 'POST') {
            // List endpoint is enriched (BookmarkSummary), POST returns
            // the bare Bookmark — but the in-memory list we surface to
            // /me/bookmarks uses the enriched fixture so the rendered
            // card has the manga title.
            bookmarks = [enrichedBookmarkFixture, ...bookmarks];
            route.fulfill({
                status: 201,
                contentType: 'application/json',
                body: JSON.stringify(bookmarkFixture)
            });
        } else {
            route.fallback();
        }
    });
    await page.route('**/api/v1/bookmarks/b1', (route) => {
        if (route.request().method() === 'DELETE') {
            bookmarks = bookmarks.filter((b) => b.id !== 'b1');
            route.fulfill({ status: 204 });
        } else {
            route.fallback();
        }
    });
}

test('authed user toggles a manga bookmark and sees it in /bookmarks', async ({ page }) => {
    await setupAuthenticatedBookmarkFlow(page);

    await page.goto(`/manga/${mangaId}`);
    const toggle = page.getByTestId('bookmark-toggle');
    await expect(toggle).toHaveText('☆ Bookmark');
    await expect(toggle).toHaveAttribute('aria-pressed', 'false');

    await toggle.click();
    await expect(toggle).toHaveText('★ Bookmarked');
    await expect(toggle).toHaveAttribute('aria-pressed', 'true');

    // The /bookmarks list reflects it.
    await page.goto('/bookmarks');
    // The /bookmarks page now renders a real card with the manga
    // title — the fixture title is "Berserk" (see mangaFixture above).
    await expect(page.getByTestId('bookmark-title')).toContainText('Berserk');
    await expect(page.getByTestId('bookmark-list')).toContainText('Whole manga');

    // Toggle off from the manga page.
    await page.goto(`/manga/${mangaId}`);
    const toggle2 = page.getByTestId('bookmark-toggle');
    await expect(toggle2).toHaveText('★ Bookmarked');
    await toggle2.click();
    await expect(toggle2).toHaveText('☆ Bookmark');
});

test('anonymous user sees a sign-in CTA instead of a toggle', async ({ page }) => {
    await page.route('**/api/v1/auth/me', (route) =>
        route.fulfill({
            status: 401,
            contentType: 'application/json',
            body: JSON.stringify({ error: { code: 'unauthenticated', message: 'unauthenticated' } })
        })
    );
    await page.route(`**/api/v1/mangas/${mangaId}`, (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify(mangaFixture)
        })
    );
    await page.route(`**/api/v1/mangas/${mangaId}/chapters?*`, (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ items: [], page: { limit: 50, offset: 0, total: null } })
        })
    );
    await page.route(`**/api/v1/mangas/${mangaId}/chapters`, (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ items: [], page: { limit: 50, offset: 0, total: null } })
        })
    );
    await page.route('**/api/v1/me/bookmarks*', (route) =>
        route.fulfill({
            status: 401,
            contentType: 'application/json',
            body: JSON.stringify({ error: { code: 'unauthenticated', message: 'unauthenticated' } })
        })
    );
    await page.route(`**/api/v1/me/read-progress/${mangaId}`, (route) =>
        route.fulfill({
            status: 401,
            contentType: 'application/json',
            body: JSON.stringify({ error: { code: 'unauthenticated', message: 'unauthenticated' } })
        })
    );
    await page.route(`**/api/v1/mangas/${mangaId}/similar`, (route) =>
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ items: [] })
        })
    );

    await page.goto(`/manga/${mangaId}`);
    await expect(page.getByTestId('bookmark-signin')).toBeVisible();
    await expect(page.getByTestId('bookmark-toggle')).toHaveCount(0);
});

test('/bookmarks page prompts anonymous users to sign in', async ({ page }) => {
    await page.route('**/api/v1/auth/me', (route) =>
        route.fulfill({
            status: 401,
            contentType: 'application/json',
            body: JSON.stringify({ error: { code: 'unauthenticated', message: 'unauthenticated' } })
        })
    );
    await page.route('**/api/v1/me/bookmarks*', (route) =>
        route.fulfill({
            status: 401,
            contentType: 'application/json',
            body: JSON.stringify({ error: { code: 'unauthenticated', message: 'unauthenticated' } })
        })
    );

    await page.goto('/bookmarks');
    await expect(page.getByTestId('bookmarks-signin')).toBeVisible();
});
