-- ADR-0017: roles are selected through the project-group control plane, not
-- through slash-command names. Existing alpha Organizations keep draft as
-- their configured default during migration; runtime code no longer hard-codes it.
ALTER TABLE "OrganizationAgentRole"
  ADD COLUMN "isDefault" BOOLEAN NOT NULL DEFAULT false;

-- An Organization without any role was valid in the previous schema (the
-- runtime failed closed later). Preserve the old alpha baseline so every
-- existing binding can acquire a selected role during this migration.
INSERT INTO "OrganizationAgentRole" (
  "id", "organizationId", "roleId", "label", "sortOrder", "isDefault", "updatedAt"
)
SELECT organization."id" || ':agent-role:draft', organization."id", 'draft', '草稿', 10, true, CURRENT_TIMESTAMP
FROM "Organization" organization
WHERE NOT EXISTS (
  SELECT 1 FROM "OrganizationAgentRole" role
  WHERE role."organizationId" = organization."id" AND role."disabledAt" IS NULL
);

WITH ranked AS (
  SELECT "id", row_number() OVER (
    PARTITION BY "organizationId"
    ORDER BY CASE WHEN "roleId" = 'draft' THEN 0 ELSE 1 END, "sortOrder", "roleId", "id"
  ) AS position
  FROM "OrganizationAgentRole"
  WHERE "disabledAt" IS NULL
)
UPDATE "OrganizationAgentRole" role
SET "isDefault" = (ranked.position = 1)
FROM ranked
WHERE role."id" = ranked."id";

CREATE UNIQUE INDEX "OrganizationAgentRole_one_active_default_per_org"
  ON "OrganizationAgentRole"("organizationId")
  WHERE "isDefault" = true AND "disabledAt" IS NULL;

ALTER TABLE "ProjectGroupBinding"
  ADD COLUMN "selectedAgentRoleId" TEXT;

UPDATE "ProjectGroupBinding" binding
SET "selectedAgentRoleId" = role."id"
FROM "Project" project
JOIN "OrganizationAgentRole" role
  ON role."organizationId" = project."organizationId"
 AND role."isDefault" = true
 AND role."disabledAt" IS NULL
WHERE binding."projectId" = project."id";

DO $$
BEGIN
  IF EXISTS (SELECT 1 FROM "ProjectGroupBinding" WHERE "selectedAgentRoleId" IS NULL) THEN
    RAISE EXCEPTION 'cannot migrate project-group bindings without an active default Agent role';
  END IF;
END $$;

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

CREATE INDEX "ProjectGroupBinding_selectedAgentRoleId_idx"
  ON "ProjectGroupBinding"("selectedAgentRoleId");

ALTER TABLE "ProjectGroupBinding"
  ADD CONSTRAINT "ProjectGroupBinding_selectedAgentRoleId_fkey"
  FOREIGN KEY ("selectedAgentRoleId") REFERENCES "OrganizationAgentRole"("id")
  ON DELETE RESTRICT ON UPDATE CASCADE;
