-- name: UpsertChapter :one
INSERT INTO chapters (
    manga_id, url, name, date_upload, chapter_number, scanlator, source_order, fetched_at
) VALUES (
    $1, $2, $3, $4, $5, $6, $7, $8
)
ON CONFLICT (manga_id, url) DO UPDATE
    SET name           = EXCLUDED.name,
        date_upload    = EXCLUDED.date_upload,
        chapter_number = EXCLUDED.chapter_number,
        scanlator      = EXCLUDED.scanlator,
        source_order   = EXCLUDED.source_order,
        fetched_at     = EXCLUDED.fetched_at
RETURNING *;

-- name: GetChapterByID :one
SELECT * FROM chapters WHERE id = $1;

-- name: ListChaptersByManga :many
SELECT * FROM chapters WHERE manga_id = $1 ORDER BY source_order;

-- name: UpdateChapterFetchedAt :exec
UPDATE chapters SET fetched_at = $2 WHERE id = $1;
