-- 004_junction_unique_constraints.sql
-- Composite UNIQUE constraints on the three org-junction tables.
--
-- Why this lives in db-init/ rather than being captured by Directus snapshot:
--   Directus's field-level `is_unique` flag only generates single-column
--   unique constraints. Junction tables need composite uniqueness on the
--   pair (org, target) so the same user/vehicle/device cannot be registered
--   twice within the same org. The snapshot YAML format does NOT capture
--   composite unique constraints, so Directus cannot round-trip them.
--   They belong here, in the same place the positions hypertable's DDL lives.
--
-- Owned by: task 1.4 (org catalog collections). The constraints are part of
-- the data model contract, not a separate Phase 1 migration concern.
--
-- Idempotency: ALTER TABLE ... ADD CONSTRAINT is NOT idempotent. The
-- migrations_applied guard table ensures this file runs at most once per
-- environment. If a constraint already exists (e.g. ad-hoc on an existing
-- stage DB), the operator must INSERT INTO migrations_applied (filename,
-- checksum) VALUES ('004_junction_unique_constraints.sql', '<sha256>') to
-- skip this file on next boot.

ALTER TABLE organization_users
  ADD CONSTRAINT organization_users_org_user_unique
  UNIQUE (organization_id, user_id);

ALTER TABLE organization_vehicles
  ADD CONSTRAINT organization_vehicles_org_vehicle_unique
  UNIQUE (organization_id, vehicle_id);

ALTER TABLE organization_devices
  ADD CONSTRAINT organization_devices_org_device_unique
  UNIQUE (organization_id, device_id);

-- -------------------------------------------------------------------------
-- 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 $$;
