-- name: UpsertProvider :one
-- Boot-time capability registration. On re-registration, capability fields
-- (kind, display_name) are refreshed; operational `status` is preserved.
INSERT INTO core.providers (slug, provider_kind, display_name, operator_surface_path)
VALUES ($1, $2, $3, $4)
ON CONFLICT (slug) DO UPDATE
SET provider_kind         = EXCLUDED.provider_kind,
    display_name          = EXCLUDED.display_name,
    operator_surface_path = EXCLUDED.operator_surface_path,
    updated_at            = NOW()
RETURNING *;

-- name: GetProvider :one
SELECT * FROM core.providers WHERE slug = $1;

-- name: ListProviders :many
SELECT * FROM core.providers ORDER BY slug;

-- name: ListProvidersByKind :many
SELECT * FROM core.providers WHERE provider_kind = $1 ORDER BY slug;

-- name: SetProviderStatus :exec
-- Operational mutation (operator-editable), distinct from capability registration.
UPDATE core.providers SET status = $2, updated_at = NOW() WHERE slug = $1;

-- name: ListPlatformResourceKeys :many
-- Platform-owned (unprefixed) resource keys, for the slug-hygiene nesting check.
SELECT resource_key FROM core.resource_keys WHERE provider IS NULL ORDER BY resource_key;

-- name: SetResourceKeyProvider :execrows
-- Stamp provider ownership on a resource key (cross-schema write, enabled by the
-- resource_keys.provider FK + this package's core_writer grant on the core
-- schema). Returns rows affected so a manifest referencing a non-existent key
-- can be detected at registration.
UPDATE core.resource_keys SET provider = $2 WHERE resource_key = $1;
