-- robot_manager v3 review fixes — phase 2 (commit 3 of 3)
-- 落地依据：docs/standards/20-database-review-checklist.md
--
-- 涵盖第二轮 finding：
--   N1 platform_master.Location.customerId 加同 schema FK constraint (原则 14)
--   N2 RobotSystemConfig 加 organizationId? + createdById? (原则 3，字典 pattern)
--   N6 SalesOrder / PurchaseOrder / RentalAgreement 加 version 乐观锁 (原则 18)
--   N3/N4/N7 纯 schema 注释 (本 migration 不含 SQL)
--
-- 注：本 migration 不包含 prisma migrate diff 自动生成的下列内容（drift 不属本 PR 主题）：
--   - 重建 partial unique constraint (commit 2 已用 raw SQL 做成 partial)
--   - platform_ai_usage 的 RenameIndex (别人留的债，单独 PR)

-- ============================================================
-- N1: Location.customerId 加 @relation FK (原则 14 - 同 schema 关联应建 DB FK)
-- onDelete: SetNull —— customer 删时 location.customerId 变 NULL，不级联删 location
-- ============================================================
ALTER TABLE "platform_master"."locations"
  ADD CONSTRAINT "locations_customer_id_fkey"
  FOREIGN KEY ("customer_id")
  REFERENCES "platform_master"."customers"("id")
  ON DELETE SET NULL ON UPDATE CASCADE;

-- ============================================================
-- N2: RobotSystemConfig 加标准字段 (原则 3，按字典 pattern - 都 nullable)
-- organizationId? = DataScope ALL；createdById? = 允许 system-seeded
-- ============================================================
ALTER TABLE "robot_manager"."robot_system_config"
  ADD COLUMN "organization_id" UUID,
  ADD COLUMN "created_by_id"   UUID;

CREATE INDEX "robot_system_config_organization_id_idx"
  ON "robot_manager"."robot_system_config"("organization_id");

-- ============================================================
-- N6: 资金敏感 L3 表加 version 乐观锁 (原则 18)
-- DEFAULT 0 既覆盖既有行回填，也是新行起始值
-- ============================================================
ALTER TABLE "robot_manager"."purchase_orders"   ADD COLUMN "version" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "robot_manager"."sales_orders"      ADD COLUMN "version" INTEGER NOT NULL DEFAULT 0;
ALTER TABLE "robot_manager"."rental_agreements" ADD COLUMN "version" INTEGER NOT NULL DEFAULT 0;
