-- ADR-0017's default-role function is total over Organizations. Enforce the
-- other side of the invariant when an Organization itself is created.
CREATE FUNCTION cph_enforce_organization_default_role() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
  active_default_count INTEGER;
BEGIN
  SELECT count(*) INTO active_default_count
  FROM "OrganizationAgentRole"
  WHERE "organizationId" = NEW."id"
    AND "isDefault" = true
    AND "disabledAt" IS NULL;

  IF active_default_count <> 1 THEN
    RAISE EXCEPTION 'Organization % must have exactly one active default Agent role; found %',
      NEW."id", active_default_count;
  END IF;
  RETURN NULL;
END;
$$;

CREATE CONSTRAINT TRIGGER "Organization_requires_active_default_role"
AFTER INSERT ON "Organization"
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION cph_enforce_organization_default_role();
