-- name: UpsertArtist :one
-- Insert or update by mbid when present; otherwise by (name, sort_name).
-- Callers pass the canonical sort_name; scanner is responsible for derivation.
INSERT INTO artists (name, sort_name, mbid)
VALUES ($1, $2, $3)
ON CONFLICT (mbid) WHERE mbid IS NOT NULL
DO UPDATE SET
    name = EXCLUDED.name,
    sort_name = EXCLUDED.sort_name,
    updated_at = now()
RETURNING *;

-- name: GetArtistByID :one
SELECT * FROM artists WHERE id = $1;

-- name: GetArtistByName :one
SELECT * FROM artists WHERE name = $1 LIMIT 1;

-- name: ListArtists :many
SELECT * FROM artists ORDER BY sort_name;

-- name: SearchArtists :many
SELECT * FROM artists
WHERE name ILIKE '%' || $1 || '%'
ORDER BY sort_name
LIMIT $2 OFFSET $3;

-- name: ListArtistsAlpha :many
SELECT * FROM artists ORDER BY sort_name, name, id LIMIT $1 OFFSET $2;

-- name: ListArtistsNewest :many
-- Secondary id tiebreaker keeps pagination stable when created_at ties.
SELECT * FROM artists ORDER BY created_at DESC, id DESC LIMIT $1 OFFSET $2;

-- name: CountArtists :one
SELECT COUNT(*) FROM artists;

-- name: CountArtistsMatching :one
SELECT COUNT(*) FROM artists WHERE name ILIKE '%' || $1::text || '%';

-- name: GetArtistsByIDs :many
-- Batched lookup used by M5c suggestion attribution to resolve top-3
-- contributing seed UUIDs back to artist names in one round-trip.
SELECT * FROM artists WHERE id = ANY($1::uuid[]);

-- name: ListArtistsAlphaWithCovers :many
-- M6a: alpha-sorted artist list with derived cover_album_id (most-recent
-- album whose cover_art_path is set). Replaces ListArtistsAlpha for the
-- /api/artists?sort=alpha branch — the new column is appended, so the
-- alpha branch is purely additive on the wire. album_count is computed
-- in the same query to drop the old N+1 in handleListArtists.
SELECT sqlc.embed(artists),
       cov.id AS cover_album_id,
       cnt.album_count::bigint AS album_count
FROM artists
LEFT JOIN LATERAL (
    SELECT id FROM albums
    WHERE artist_id = artists.id AND cover_art_path IS NOT NULL
    ORDER BY created_at DESC LIMIT 1
) cov ON true
LEFT JOIN LATERAL (
    SELECT count(*) AS album_count
    FROM albums WHERE artist_id = artists.id
) cnt ON true
ORDER BY artists.sort_name, artists.name, artists.id
LIMIT $1 OFFSET $2;

-- name: DeleteArtistIfEmpty :one
-- M7 #372: deletes the artist row only when it has no remaining albums
-- AND no remaining tracks (defensive — tracks can in principle exist
-- without an album, though the scanner doesn't write that shape today).
DELETE FROM artists a
WHERE a.id = $1
  AND NOT EXISTS (SELECT 1 FROM albums al WHERE al.artist_id = a.id)
  AND NOT EXISTS (SELECT 1 FROM tracks t WHERE t.artist_id = a.id)
RETURNING a.id;
