-- ============================================
-- 系统账户转出订单表
-- 用于记录从系统账户(S开头/区域账户)转出到用户账户的订单
-- ============================================

CREATE TABLE IF NOT EXISTS "system_withdrawal_orders" (
    "order_id" BIGSERIAL PRIMARY KEY,
    "order_no" VARCHAR(50) NOT NULL UNIQUE,

    -- 转出方(系统账户)
    "from_account_sequence" VARCHAR(20) NOT NULL,    -- 系统账户序列号 (S0000000001, 9440000, 8440100 等)
    "from_account_name" VARCHAR(100) NOT NULL,       -- 系统账户名称 (总部账户, 广东省区域 等)

    -- 接收方(用户账户)
    "to_account_sequence" VARCHAR(20) NOT NULL,      -- 用户充值ID (D...)
    "to_user_id" BIGINT NOT NULL,                    -- 用户ID
    "to_user_name" VARCHAR(100),                     -- 用户姓名
    "to_address" VARCHAR(100) NOT NULL,              -- 用户区块链地址

    -- 金额
    "amount" DECIMAL(20, 8) NOT NULL,                -- 转出金额
    "chain_type" VARCHAR(20) NOT NULL DEFAULT 'KAVA', -- 链类型

    -- 交易信息
    "tx_hash" VARCHAR(100),                          -- 链上交易哈希

    -- 状态: PENDING -> FROZEN -> BROADCASTED -> CONFIRMED / FAILED
    "status" VARCHAR(20) NOT NULL DEFAULT 'PENDING',
    "error_message" VARCHAR(500),

    -- 操作者
    "operator_id" VARCHAR(100) NOT NULL,             -- 操作管理员ID
    "operator_name" VARCHAR(100),                    -- 操作管理员姓名

    -- 备注
    "memo" TEXT,

    -- 时间戳
    "frozen_at" TIMESTAMP,
    "broadcasted_at" TIMESTAMP,
    "confirmed_at" TIMESTAMP,
    "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- 索引
CREATE INDEX "idx_system_withdrawal_from_account" ON "system_withdrawal_orders" ("from_account_sequence");
CREATE INDEX "idx_system_withdrawal_to_account" ON "system_withdrawal_orders" ("to_account_sequence");
CREATE INDEX "idx_system_withdrawal_to_user" ON "system_withdrawal_orders" ("to_user_id");
CREATE INDEX "idx_system_withdrawal_status" ON "system_withdrawal_orders" ("status");
CREATE INDEX "idx_system_withdrawal_tx_hash" ON "system_withdrawal_orders" ("tx_hash");
CREATE INDEX "idx_system_withdrawal_operator" ON "system_withdrawal_orders" ("operator_id");
CREATE INDEX "idx_system_withdrawal_created" ON "system_withdrawal_orders" ("created_at");