import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/svelte';
import DeadJobsTable from './DeadJobsTable.svelte';
import type { DeadJob } from '$lib/api/admin';

afterEach(() => cleanup());

function deadJob(overrides: Partial<DeadJob>): DeadJob {
    return {
        id: 'job-1',
        kind: 'sync_chapter_content',
        chapter_id: null,
        manga_id: null,
        manga_title: null,
        chapter_number: null,
        payload_title: null,
        source_url: null,
        source_key: null,
        attempts: 5,
        max_attempts: 5,
        last_error: 'boom',
        updated_at: '2026-06-16T00:00:00Z',
        ...overrides
    };
}

function baseProps(jobs: DeadJob[]) {
    return {
        jobs,
        total: jobs.length,
        page: 1,
        totalPages: 1,
        search: '',
        busy: false,
        onSearch: () => {},
        onPageChange: () => {},
        onRequeue: () => {},
        onRequeueAll: () => {}
    };
}

describe('DeadJobsTable', () => {
    it('prefers manga_title when present', () => {
        const jobs = [deadJob({ manga_title: 'Naruto', chapter_number: 700 })];
        render(DeadJobsTable, { props: baseProps(jobs) });
        expect(screen.getByText(/Naruto/)).toBeTruthy();
    });

    it('falls back to payload_title (linked to source_url) for a sync_manga job with no manga row', () => {
        const jobs = [
            deadJob({
                kind: 'sync_manga',
                manga_title: null,
                payload_title: 'Ghost Manga',
                source_url: 'http://x/manga/gone-1',
                source_key: 'gone-1'
            })
        ];
        render(DeadJobsTable, { props: baseProps(jobs) });
        const link = screen.getByRole('link', { name: 'Ghost Manga' }) as HTMLAnchorElement;
        expect(link.getAttribute('href')).toBe('http://x/manga/gone-1');
    });

    it('falls back to source_key when there is no title at all', () => {
        const jobs = [deadJob({ kind: 'sync_manga', source_key: 'only-key' })];
        render(DeadJobsTable, { props: baseProps(jobs) });
        expect(screen.getByText('only-key')).toBeTruthy();
    });
});
