-- name: UpsertManga :one
INSERT INTO manga (
    source_id, url, title, artist, author, description, genre,
    status, thumbnail_url, initialized, last_fetched_at
) VALUES (
    $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11
)
ON CONFLICT (source_id, url) DO UPDATE
    SET title           = EXCLUDED.title,
        artist          = EXCLUDED.artist,
        author          = EXCLUDED.author,
        description     = EXCLUDED.description,
        genre           = EXCLUDED.genre,
        status          = EXCLUDED.status,
        thumbnail_url   = EXCLUDED.thumbnail_url,
        initialized     = EXCLUDED.initialized,
        last_fetched_at = EXCLUDED.last_fetched_at
RETURNING *;

-- name: GetMangaBySourceURL :one
SELECT * FROM manga WHERE source_id = $1 AND url = $2;

-- name: GetMangaByID :one
SELECT * FROM manga WHERE id = $1;

-- name: ListMangaBySource :many
SELECT * FROM manga
WHERE source_id = $1
ORDER BY last_fetched_at DESC;

-- name: UpdateMangaDetails :exec
UPDATE manga
SET artist        = $2,
    author        = $3,
    description   = $4,
    genre         = $5,
    status        = $6,
    thumbnail_url = $7,
    initialized   = TRUE
WHERE id = $1;

-- name: UpdateMangaFetchedAt :exec
UPDATE manga SET last_fetched_at = $2 WHERE id = $1;

-- name: UpdateChaptersFetchedAt :exec
UPDATE manga SET chapters_last_fetched_at = $2 WHERE id = $1;
