-- 0008_approvals_idempotency_nulls_not_distinct.sql — fix the partial unique
-- index on `approvals` so the `ON CONFLICT (workspace_id, topic,
-- idempotency_key)` upsert in `apps/cli` reuses an existing row when
-- `workspace_id IS NULL` (the local emulator never populates it).
--
-- Postgres treats NULL as distinct in unique indexes by default, so two
-- inserts with the same (NULL, topic, idempotencyKey) tuple were both
-- accepted instead of round-tripping the original approvalId. `NULLS NOT
-- DISTINCT` (Postgres 15+) collapses NULLs into a single comparable value,
-- which preserves the cloud semantics (workspace_id NOT NULL) and unblocks
-- the local emulator path.
--
-- Spec: docs/arquitectura/specs/stackbone-agent-protocol-v1.md §6.6.

DROP INDEX IF EXISTS stackbone_platform.approvals_idempotency_uq;

CREATE UNIQUE INDEX IF NOT EXISTS approvals_idempotency_uq
    ON stackbone_platform.approvals (workspace_id, topic, idempotency_key) NULLS NOT DISTINCT
    WHERE idempotency_key IS NOT NULL;
