-- ADR-0017 / ADR-0020: enforce the selected role's Organization at the
-- database boundary. A role primary key alone cannot prove tenant scope.
ALTER TABLE "ProjectGroupBinding"
  ADD COLUMN "organizationId" TEXT;

UPDATE "ProjectGroupBinding" binding
SET "organizationId" = project."organizationId"
FROM "Project" project
WHERE project."id" = binding."projectId";

DO $$
BEGIN
  IF EXISTS (SELECT 1 FROM "ProjectGroupBinding" WHERE "organizationId" IS NULL) THEN
    RAISE EXCEPTION 'cannot tenant-scope project-group binding without a project Organization';
  END IF;
END $$;

ALTER TABLE "ProjectGroupBinding"
  ALTER COLUMN "organizationId" SET NOT NULL;

CREATE UNIQUE INDEX "Project_organizationId_id_key"
  ON "Project"("organizationId", "id");

ALTER TABLE "ProjectGroupBinding"
  DROP CONSTRAINT "ProjectGroupBinding_projectId_fkey",
  DROP CONSTRAINT "ProjectGroupBinding_selectedAgentRoleId_fkey";

ALTER TABLE "ProjectGroupBinding"
  ADD CONSTRAINT "ProjectGroupBinding_organizationId_fkey"
    FOREIGN KEY ("organizationId") REFERENCES "Organization"("id")
    ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT "ProjectGroupBinding_organizationId_projectId_fkey"
    FOREIGN KEY ("organizationId", "projectId") REFERENCES "Project"("organizationId", "id")
    ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT "ProjectGroupBinding_organizationId_selectedAgentRoleId_fkey"
    FOREIGN KEY ("organizationId", "selectedAgentRoleId")
    REFERENCES "OrganizationAgentRole"("organizationId", "id")
    ON DELETE RESTRICT ON UPDATE CASCADE;

CREATE INDEX "ProjectGroupBinding_organizationId_idx"
  ON "ProjectGroupBinding"("organizationId");
