-- 1. KpiAssignment.name: NULL → 默认名称
UPDATE "platform_performance"."kpi_assignment"
  SET "name" = '未命名 KPI'
  WHERE "name" IS NULL;

-- 2. 去重：同一员工同一周期下名称重复的 KPI，追加序号
WITH duplicates AS (
  SELECT id, ROW_NUMBER() OVER (
    PARTITION BY "cycle_id", "employee_id", "name"
    ORDER BY "created_at"
  ) AS rn
  FROM "platform_performance"."kpi_assignment"
  WHERE "deleted_at" IS NULL
)
UPDATE "platform_performance"."kpi_assignment" ka
  SET "name" = ka."name" || ' (' || d.rn || ')'
  FROM duplicates d
  WHERE ka.id = d.id AND d.rn > 1;

-- 3. 设为 NOT NULL
ALTER TABLE "platform_performance"."kpi_assignment"
  ALTER COLUMN "name" SET NOT NULL;

-- 4. KpiAssignment 防重约束（partial unique，排除软删除）
CREATE UNIQUE INDEX "kpi_assignment_cycleId_employeeId_name_key"
  ON "platform_performance"."kpi_assignment"("cycle_id", "employee_id", "name")
  WHERE "deleted_at" IS NULL;

-- 5. Evaluation360 补充索引
CREATE INDEX "evaluation_360_cycleId_targetId_status_idx"
  ON "platform_performance"."evaluation_360"("cycle_id", "target_id", "status");
