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

// Detail-page like/dislike toggle: reflects initial state, sets/switches via
// PUT, and clears the active reaction via DELETE.

const mangaId = 'a1111111-1111-1111-1111-111111111111';

type Captured = { method: string; reaction?: string };

async function mockDetail(page: Page, captured: Captured[]) {
    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: [], page: { limit: 50, offset: 0, total: 0 } }) })
    );
    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: 404, contentType: 'application/json', body: JSON.stringify({ error: { code: 'not_found', message: 'no' } }) })
    );
    // Reaction: initially unset; capture writes.
    await page.route(`**/api/v1/me/reactions/${mangaId}`, (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ manga_id: mangaId, reaction: null }) })
    );
    await page.route(`**/api/v1/mangas/${mangaId}/reaction`, (route) => {
        const method = route.request().method();
        if (method === 'PUT') {
            const reaction = route.request().postDataJSON()?.reaction as string;
            captured.push({ method, reaction });
            return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ manga_id: mangaId, reaction }) });
        }
        captured.push({ method });
        return route.fulfill({ status: 204, body: '' });
    });
    // getManga last so it wins over the chapters glob.
    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('like, switch to dislike, then clear', async ({ page }) => {
    const captured: Captured[] = [];
    await mockDetail(page, captured);
    await page.goto(`/manga/${mangaId}`);

    const like = page.getByTestId('reaction-like');
    const dislike = page.getByTestId('reaction-dislike');
    await expect(like).toHaveAttribute('aria-pressed', 'false');
    await expect(dislike).toHaveAttribute('aria-pressed', 'false');

    // Like.
    await like.click();
    await expect(like).toHaveAttribute('aria-pressed', 'true');
    await expect.poll(() => captured.at(-1)).toEqual({ method: 'PUT', reaction: 'like' });

    // Switch to dislike.
    await dislike.click();
    await expect(dislike).toHaveAttribute('aria-pressed', 'true');
    await expect(like).toHaveAttribute('aria-pressed', 'false');
    await expect.poll(() => captured.at(-1)).toEqual({ method: 'PUT', reaction: 'dislike' });

    // Click the active dislike again → clear.
    await dislike.click();
    await expect(dislike).toHaveAttribute('aria-pressed', 'false');
    await expect.poll(() => captured.at(-1)?.method).toBe('DELETE');
});
