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

// Homepage "Recommended for you" shelf: visible with cards when signed in and
// the feed is non-empty; absent for anonymous visitors (401 → empty).

const emptyMangas = { items: [], page: { limit: 50, offset: 0, total: 0 } };

function manga(id: string, title: string) {
    return {
        id, title, 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: []
    };
}

async function mockCommon(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/genres*', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: '[]' })
    );
    await page.route('**/api/v1/mangas*', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(emptyMangas) })
    );
    // Keep the Continue-reading shelf out of the way.
    await page.route('**/api/v1/me/read-progress*', (r) =>
        r.fulfill({ status: 401, contentType: 'application/json', body: JSON.stringify({ error: { code: 'unauthenticated', message: 'no' } }) })
    );
}

test('shows the recommendations shelf with cards when signed in', async ({ page }) => {
    await mockCommon(page);
    await page.route('**/api/v1/auth/me', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ user: { id: 'u1', username: 'reader', is_admin: false } }) })
    );
    await page.route('**/api/v1/me/recommendations*', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [manga('m1', 'Berserk'), manga('m2', 'Vinland')] }) })
    );

    await page.goto('/');
    await expect(page.getByTestId('recommendations-shelf')).toBeVisible();
    await expect(page.getByTestId('rec-card-m1')).toBeVisible();
    await expect(page.getByTestId('rec-card-m2')).toBeVisible();
});

test('hides the recommendations shelf for anonymous visitors', async ({ page }) => {
    await mockCommon(page);
    await page.route('**/api/v1/auth/me', (r) =>
        r.fulfill({ status: 401, contentType: 'application/json', body: JSON.stringify({ error: { code: 'unauthenticated', message: 'no' } }) })
    );
    await page.route('**/api/v1/me/recommendations*', (r) =>
        r.fulfill({ status: 401, contentType: 'application/json', body: JSON.stringify({ error: { code: 'unauthenticated', message: 'no' } }) })
    );

    await page.goto('/');
    await expect(page.getByRole('heading', { name: 'Mangas' })).toBeVisible();
    await expect(page.getByTestId('recommendations-shelf')).toHaveCount(0);
});
