-- M7 cover-sources: queries for the cover_art_provider_settings table
-- and the cover_art_sources_meta singleton. The SettingsService
-- consumes these.

-- name: ListProviderSettings :many
-- Returns all rows from cover_art_provider_settings. Used by the
-- SettingsService at boot for reconciliation and by the admin GET
-- handler.
SELECT provider_id, enabled, api_key, display_order, created_at, updated_at
  FROM cover_art_provider_settings
 ORDER BY display_order, provider_id;

-- name: UpsertProviderSettings :exec
-- INSERT a default row for a newly-registered provider, or update an
-- existing row's display_order on boot reconciliation. Does NOT
-- overwrite enabled / api_key on conflict — the operator's settings
-- persist across restarts.
INSERT INTO cover_art_provider_settings (provider_id, enabled, display_order)
VALUES ($1, $2, $3)
ON CONFLICT (provider_id) DO UPDATE
   SET display_order = EXCLUDED.display_order,
       updated_at    = now();

-- name: UpdateProviderSettings :exec
-- Admin PATCH applies one or both fields. Pass NULL for enabled to
-- leave it unchanged. Pass FALSE for the apiKeyChanged flag to leave
-- the api_key unchanged regardless of apiKey value; pass TRUE with
-- empty string to clear, or TRUE with non-empty to set.
UPDATE cover_art_provider_settings
   SET enabled    = COALESCE($2, enabled),
       api_key    = CASE WHEN $3::boolean THEN $4 ELSE api_key END,
       updated_at = now()
 WHERE provider_id = $1;

-- name: GetCurrentSourcesVersion :one
SELECT current_version FROM cover_art_sources_meta WHERE id = true;

-- name: BumpSourcesVersion :one
-- Increments and returns the new version. Called by SettingsService
-- only when the *enabled set* changes (not on key/display_order
-- changes). RETURNING gives the new value back so the handler can
-- include it in the response without a follow-up SELECT.
UPDATE cover_art_sources_meta
   SET current_version = current_version + 1
 WHERE id = true
RETURNING current_version;

-- name: GetCoverArtProvidersHash :one
SELECT last_registered_providers_hash
  FROM cover_art_sources_meta
 WHERE id = true;

-- name: BumpVersionAndSetProvidersHash :one
-- Atomically increments the version and stores the new provider-set
-- hash. Called at boot when the registered-provider set has changed
-- since the last start, so 'none' rows become eligible for retry.
-- RETURNING gives the new version without a follow-up SELECT.
UPDATE cover_art_sources_meta
   SET current_version = current_version + 1,
       last_registered_providers_hash = $1
 WHERE id = true
RETURNING current_version;
