DROP INDEX IF EXISTS idx_inspection_records_user_idempotency;

-- 恢复全局唯一索引前，先处理跨用户重复，保留所有记录。
UPDATE inspection_records AS r
SET idempotency_key = r.idempotency_key || '#' || r.id
WHERE r.idempotency_key IS NOT NULL
  AND EXISTS (
      SELECT 1
      FROM inspection_records AS x
      WHERE x.idempotency_key = r.idempotency_key
        AND x.id <> r.id
  );

CREATE UNIQUE INDEX IF NOT EXISTS idx_inspection_records_idempotency_key
    ON inspection_records (idempotency_key)
    WHERE idempotency_key IS NOT NULL;
