-- 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 || '%';
