-- PR1 — L1b 字典 + RobotLifecycleStage enum atomic 扩值
-- 参考: docs/modules/robot-manager/business-analysis/重构方案.md §3
--
-- 改动分两段：
--   A. 新建 platform_master schema + 5 个字典/参考表
--   B. RobotStatus enum 重命名 + atomic 扩值（保留旧值，PR3 删）+ 新增模块 enum
--
-- 注：PR1 零侵入策略 — 数据保持 v2 旧值，service 层 default + VALID_TRANSITIONS 仍 v2，
--      PR3 重写状态机时统一迁数据 + 切 service 层。本 migration 不含 UPDATE 数据。

-- ============================================================
-- A. platform_master schema + 字典表
-- ============================================================

CREATE SCHEMA IF NOT EXISTS "platform_master";

-- 注：字典 / 参考表都加 standard 04 标准字段（id / createdById / organizationId）；
-- organizationId nullable 表全局共享（DataScope 配置按 ALL 处理，详见 standard 04 §禁止段）

-- A.1 currencies
CREATE TABLE "platform_master"."currencies" (
  "id"              UUID PRIMARY KEY,
  "code"            VARCHAR(3) NOT NULL,
  "name"            TEXT NOT NULL,
  "symbol"          TEXT,
  "decimals"        INTEGER NOT NULL DEFAULT 2,
  "enabled"         BOOLEAN NOT NULL DEFAULT true,
  "organization_id" UUID,
  "created_at"      TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at"      TIMESTAMPTZ(3) NOT NULL,
  "created_by_id"   UUID
);
CREATE UNIQUE INDEX "currencies_code_key" ON "platform_master"."currencies"("code");
CREATE INDEX "currencies_enabled_idx" ON "platform_master"."currencies"("enabled");
CREATE INDEX "currencies_organization_id_idx" ON "platform_master"."currencies"("organization_id");

-- A.2 countries
CREATE TABLE "platform_master"."countries" (
  "id"              UUID PRIMARY KEY,
  "code"            VARCHAR(2) NOT NULL,
  "iso3"            VARCHAR(3) NOT NULL,
  "name"            TEXT NOT NULL,
  "region"          TEXT,
  "enabled"         BOOLEAN NOT NULL DEFAULT true,
  "organization_id" UUID,
  "created_at"      TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at"      TIMESTAMPTZ(3) NOT NULL,
  "created_by_id"   UUID
);
CREATE UNIQUE INDEX "countries_code_key" ON "platform_master"."countries"("code");
CREATE UNIQUE INDEX "countries_iso3_key" ON "platform_master"."countries"("iso3");
CREATE INDEX "countries_enabled_idx" ON "platform_master"."countries"("enabled");
CREATE INDEX "countries_region_idx" ON "platform_master"."countries"("region");
CREATE INDEX "countries_organization_id_idx" ON "platform_master"."countries"("organization_id");

-- A.3 geo_regions（重命名避免跟 corp_hr.Region 冲突）
CREATE TABLE "platform_master"."geo_regions" (
  "id"              UUID PRIMARY KEY,
  "code"            VARCHAR(8) NOT NULL,
  "name"            TEXT NOT NULL,
  "countries"       TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
  "enabled"         BOOLEAN NOT NULL DEFAULT true,
  "organization_id" UUID,
  "created_at"      TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at"      TIMESTAMPTZ(3) NOT NULL,
  "created_by_id"   UUID
);
CREATE UNIQUE INDEX "geo_regions_code_key" ON "platform_master"."geo_regions"("code");
CREATE INDEX "geo_regions_enabled_idx" ON "platform_master"."geo_regions"("enabled");
CREATE INDEX "geo_regions_organization_id_idx" ON "platform_master"."geo_regions"("organization_id");

-- A.4 units_of_measure
CREATE TABLE "platform_master"."units_of_measure" (
  "id"              UUID PRIMARY KEY,
  "code"            VARCHAR(8) NOT NULL,
  "name"            TEXT NOT NULL,
  "category"        TEXT,
  "enabled"         BOOLEAN NOT NULL DEFAULT true,
  "organization_id" UUID,
  "created_at"      TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at"      TIMESTAMPTZ(3) NOT NULL,
  "created_by_id"   UUID
);
CREATE UNIQUE INDEX "units_of_measure_code_key" ON "platform_master"."units_of_measure"("code");
CREATE INDEX "units_of_measure_enabled_idx" ON "platform_master"."units_of_measure"("enabled");
CREATE INDEX "units_of_measure_category_idx" ON "platform_master"."units_of_measure"("category");
CREATE INDEX "units_of_measure_organization_id_idx" ON "platform_master"."units_of_measure"("organization_id");

-- A.5 dictionaries (通用字典：label_type / tariff_type / declaration_type / service_issue_type / industry 等)
CREATE TABLE "platform_master"."dictionaries" (
  "id"              UUID PRIMARY KEY,
  "category"        VARCHAR(32) NOT NULL,
  "code"            VARCHAR(64) NOT NULL,
  "label_en"        TEXT NOT NULL,
  "label_zh"        TEXT,
  "sort_order"      INTEGER NOT NULL DEFAULT 0,
  "enabled"         BOOLEAN NOT NULL DEFAULT true,
  "metadata"        JSONB NOT NULL DEFAULT '{}',
  "organization_id" UUID,
  "created_at"      TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at"      TIMESTAMPTZ(3) NOT NULL,
  "created_by_id"   UUID
);
CREATE UNIQUE INDEX "dictionaries_category_code_key" ON "platform_master"."dictionaries"("category", "code");
CREATE INDEX "dictionaries_category_enabled_sort_order_idx"
  ON "platform_master"."dictionaries"("category", "enabled", "sort_order");
CREATE INDEX "dictionaries_organization_id_idx" ON "platform_master"."dictionaries"("organization_id");

-- ============================================================
-- B. RobotStatus enum 重命名 + atomic 扩值
-- ============================================================

-- B.1 RENAME 现有 RobotStatus → RobotLifecycleStage（Postgres ALTER TYPE RENAME 兼容事务）
ALTER TYPE "robot_manager"."RobotStatus" RENAME TO "RobotLifecycleStage";

-- B.2 原地扩 19 个新 stage 值（含部门前缀）
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'SUPPLY_PO_CREATED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'SUPPLY_IN_PRODUCTION';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'SUPPLY_READY_TO_SHIP';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'LOGISTICS_IN_TRANSIT';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'LOGISTICS_BONDED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'LOGISTICS_CUSTOMS_CLEARED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'WAREHOUSE_RECEIVED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'WAREHOUSE_AT_W1_PDI';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'WAREHOUSE_MODIFICATION';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'WAREHOUSE_AT_W2';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'WAREHOUSE_AT_W2_RLE';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'WAREHOUSE_BRANDED_READY';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'SALES_RESERVED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'SALES_PAYMENT_VALIDATED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'DELIVERY_APPROVAL';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'DELIVERY_PAYMENT_COLLECTED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'DELIVERY_READY';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'DELIVERY_DELIVERED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'RENTAL_ACTIVE';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'AFTERSALES_TICKET';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'AFTERSALES_RETURN_INITIATED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'AFTERSALES_RETURN_RECEIVED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'AFTERSALES_AT_W6';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'AFTERSALES_UNDER_REPAIR';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'AFTERSALES_QUOTE_APPROVAL';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'AFTERSALES_REPAIRED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'CLOSED';
ALTER TYPE "robot_manager"."RobotLifecycleStage" ADD VALUE IF NOT EXISTS 'RETURNED';
-- CANCELLED / RESERVED / DELIVERED 旧值跟新值同名，无需扩

-- B.3 新增 RobotUsageType / RobotDisposalType
CREATE TYPE "robot_manager"."RobotUsageType" AS ENUM (
  'SALES', 'RND', 'MARKETING', 'CAPITAL', 'PRODUCT', 'TO_AGIBOT', 'LAUNCH_EVENT'
);
CREATE TYPE "robot_manager"."RobotDisposalType" AS ENUM (
  'SCRAPPED', 'SWAPPED_TO_AGIBOT', 'CANCELLED'
);

-- B.4 L3 业务表 enum（PR4 才用，PR1 先建好）
CREATE TYPE "robot_manager"."PurchaseOrderStatus" AS ENUM (
  'DRAFT', 'ORDERED', 'PARTIAL_RECEIVED', 'RECEIVED', 'CLOSED', 'CANCELLED'
);
CREATE TYPE "robot_manager"."SalesOrderStatus" AS ENUM (
  'RESERVED', 'PENDING', 'APPROVED', 'FULFILLING', 'COMPLETED', 'CANCELLED'
);
CREATE TYPE "robot_manager"."SalesContractStatus" AS ENUM (
  'DRAFT', 'SIGNED', 'VOID'
);
CREATE TYPE "robot_manager"."SalesLineType" AS ENUM (
  'HARDWARE', 'SOFTWARE', 'COCREATION'
);
CREATE TYPE "robot_manager"."DeliveryRequestType" AS ENUM (
  'WILL_CALL', 'THREE_PL', 'WHITE_GLOVE'
);
CREATE TYPE "robot_manager"."DeliveryRequestStatus" AS ENUM (
  'REQUESTED', 'APPROVED', 'FULFILLING', 'COMPLETED', 'CANCELLED'
);
CREATE TYPE "robot_manager"."DeliveryFormStatus" AS ENUM (
  'DRAFT', 'SIGNED', 'REJECTED'
);
CREATE TYPE "robot_manager"."RevenueRecognitionStatus" AS ENUM (
  'PENDING', 'RECOGNIZED', 'ADJUSTED'
);
CREATE TYPE "robot_manager"."InvoiceStatus" AS ENUM (
  'PENDING', 'ISSUED', 'PAID', 'OVERDUE'
);
CREATE TYPE "robot_manager"."PaymentRelatedType" AS ENUM (
  'SALES_ORDER', 'PURCHASE_ORDER'
);
CREATE TYPE "robot_manager"."PaymentDirection" AS ENUM (
  'INBOUND', 'OUTBOUND'
);
CREATE TYPE "robot_manager"."PaymentMethod" AS ENUM (
  'DEPOSIT_TRANSFER', 'CHECK', 'ACH', 'LEASE',
  'FULL_PAYMENT_CHECK', 'FULL_PAYMENT_WIRE', 'CO_CREATION_CREDIT', 'WIRE_TRANSFER'
);
CREATE TYPE "robot_manager"."PaymentStatus" AS ENUM (
  'NOT_PAID_YET', 'PARTIAL', 'PAID', 'CANCELLED', 'DRAFT'
);
CREATE TYPE "robot_manager"."PreDelContractStatus" AS ENUM (
  'PENDING', 'SIGNED', 'COMPLETED'
);
CREATE TYPE "robot_manager"."QualityLabelStatus" AS ENUM (
  'PENDING', 'APPLIED', 'VERIFIED', 'REJECTED'
);
CREATE TYPE "robot_manager"."LogisticsStatus" AS ENUM (
  'SHIPPED', 'IN_TRANSIT', 'ARRIVED', 'DELAYED', 'CUSTOMS_HOLD'
);
CREATE TYPE "robot_manager"."StickerStatus" AS ENUM (
  'NONE', 'PARTIAL', 'COMPLETE'
);
CREATE TYPE "robot_manager"."FccStatus" AS ENUM (
  'PENDING', 'CLEARED', 'REJECTED'
);
CREATE TYPE "robot_manager"."TicketSeverity" AS ENUM (
  'P0', 'P1', 'P2', 'P3'
);
CREATE TYPE "robot_manager"."ServiceTicketStatus" AS ENUM (
  'NEW', 'IN_PROGRESS', 'AWAITING_CUSTOMER', 'RESOLVED', 'CLOSED'
);
CREATE TYPE "robot_manager"."RobotPhysicalStatus" AS ENUM (
  'STORED', 'IN_TRANSIT', 'DELIVERED', 'IN_SERVICE', 'RETIRED'
);
CREATE TYPE "robot_manager"."RobotWarrantyStatus" AS ENUM (
  'INACTIVE', 'ACTIVE', 'EXPIRED', 'VOIDED'
);
CREATE TYPE "robot_manager"."RentalAgreementStatus" AS ENUM (
  'ACTIVE', 'EXPIRED', 'TERMINATED'
);
CREATE TYPE "robot_manager"."ImportRecordStatus" AS ENUM (
  'OK', 'CONFLICT', 'PHANTOM'
);
