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

// Streamed loaders (bookmarks / collections / library / search) capture a
// failed fetch into an in-band `error` field so the page renders an inline
// message instead of either the framework error page (network failure —
// a non-ApiError) or a misleading empty state (an HTTP error). These specs
// drive each distinct loader shape into that error path.

const collectionId = 'd2222222-2222-2222-2222-222222222222';

async function authed(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: 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/files/**', (r) => r.fulfill({ status: 200, body: '' }));
}

test('bookmarks: a network failure renders inline, not the framework error page', async ({ page }) => {
    await authed(page);
    // A raw connection failure surfaces as a non-ApiError (TypeError) from
    // fetch — the case that previously escaped to the framework boundary.
    await page.route('**/api/v1/me/bookmarks*', (r) => r.abort());

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

test('library: a network failure on one of the aggregated fetches renders inline', async ({ page }) => {
    await authed(page);
    await page.route('**/api/v1/me/collections*', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [], page: { limit: 200, offset: 0, total: 0 } }) })
    );
    await page.route('**/api/v1/me/read-progress*', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [], page: { limit: 100, offset: 0, total: 0 } }) })
    );
    await page.route('**/api/v1/me/page-tags/distinct*', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [] }) })
    );
    await page.route('**/api/v1/me/page-tags?**', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [], page: { limit: 100, offset: 0, total: 0 } }) })
    );
    await page.route('**/api/v1/me/bookmarks*', (r) => r.abort());

    await page.goto('/library');
    await expect(page.getByTestId('library-error')).toBeVisible();
});

test('search: a failed results query shows an error, not a false "no matches"', async ({ page }) => {
    await authed(page);
    await page.route('**/api/v1/me/page-tags/distinct*', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [{ tag: 'funny', count: 3 }] }) })
    );
    // The streamed tagged-pages query fails with a server error.
    await page.route('**/api/v1/me/page-tags?**', (r) =>
        r.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ error: { code: 'internal_error', message: 'boom' } }) })
    );

    await page.goto('/search?tag=funny');
    // The chip cloud / active tag renders (distinct resolved) ...
    await expect(page.getByTestId('search-active-tag')).toBeVisible();
    // ... and the failed results render as an error, not "No pages tagged".
    await expect(page.getByTestId('search-results-error')).toBeVisible();
    await expect(page.getByTestId('search-pages-empty')).toHaveCount(0);
});

test('collection detail: a failed content load shows an inline error, not an empty collection', async ({ page }) => {
    await authed(page);
    await page.route(`**/api/v1/collections/${collectionId}`, (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ id: collectionId, name: 'Favourites', description: null, manga_count: 1 }) })
    );
    await page.route(`**/api/v1/collections/${collectionId}/pages*`, (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [], page: { limit: 200, offset: 0, total: 0 } }) })
    );
    await page.route(`**/api/v1/collections/${collectionId}/mangas*`, (r) =>
        r.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ error: { code: 'internal_error', message: 'boom' } }) })
    );

    await page.goto(`/collections/${collectionId}`);
    await expect(page.getByRole('heading', { name: 'Favourites' })).toBeVisible();
    await expect(page.getByTestId('collection-content-error')).toBeVisible();
    await expect(page.getByTestId('collection-empty')).toHaveCount(0);
});
