-- 001_junction_unique_constraints.sql (post-schema phase)
-- Composite UNIQUE constraints on the org-junction tables.
--
-- Why post-schema?
--   The tables this migration constrains (organization_users,
--   organization_vehicles, organization_devices) are Directus-managed —
--   created by `directus schema apply` from snapshots/schema.yaml during
--   entrypoint step 2/5.  Pre-schema migrations (db-init/) cannot reference
--   them because they don't exist yet at that point.  This file lives in
--   db-init-post/ which the runner walks AFTER schema-apply.
--
-- Why composite uniqueness lives here at all (not in the snapshot YAML)?
--   Directus's snapshot format only captures single-column unique
--   constraints (the field-level `is_unique` flag).  Composite uniqueness
--   is enforced via raw DDL.
--
-- Idempotency: each ALTER TABLE is wrapped in a `pg_constraint` existence
--   check so the migration is safe to apply against a database where the
--   constraints were created out-of-band (e.g. via psql during the dev
--   recovery from the schema-apply destructive-delete incident in task
--   1.5).  The runner's checksum guard is a separate layer; this guard
--   protects against state drift that the runner can't see.

DO $$ BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'organization_users_org_user_unique'
  ) THEN
    ALTER TABLE organization_users
      ADD CONSTRAINT organization_users_org_user_unique
      UNIQUE (organization_id, user_id);
  END IF;
END $$;

DO $$ BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'organization_vehicles_org_vehicle_unique'
  ) THEN
    ALTER TABLE organization_vehicles
      ADD CONSTRAINT organization_vehicles_org_vehicle_unique
      UNIQUE (organization_id, vehicle_id);
  END IF;
END $$;

DO $$ BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'organization_devices_org_device_unique'
  ) THEN
    ALTER TABLE organization_devices
      ADD CONSTRAINT organization_devices_org_device_unique
      UNIQUE (organization_id, device_id);
  END IF;
END $$;

-- -------------------------------------------------------------------------
-- Assertion block: verify all three constraints landed.
-- -------------------------------------------------------------------------
DO $$ BEGIN

  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint
    WHERE conname = 'organization_users_org_user_unique'
  ) THEN
    RAISE EXCEPTION 'organization_users composite unique constraint missing';
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint
    WHERE conname = 'organization_vehicles_org_vehicle_unique'
  ) THEN
    RAISE EXCEPTION 'organization_vehicles composite unique constraint missing';
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint
    WHERE conname = 'organization_devices_org_device_unique'
  ) THEN
    RAISE EXCEPTION 'organization_devices composite unique constraint missing';
  END IF;

END $$;
