-- 创建充值订单表 tb_recharge_order
-- 承接原 tb_asset_recharge_record 的业务字段 + 增加与资产的直接关联
CREATE TABLE tb_recharge_order (
    id                   BIGSERIAL PRIMARY KEY,
    recharge_order_no    VARCHAR(40)  NOT NULL UNIQUE,   -- 沿用 CRCH 前缀
    user_id              BIGINT       NOT NULL,           -- 发起用户（个人客户 ID）
    asset_wallet_id      BIGINT       NOT NULL,
    resource_type        VARCHAR(20)  NOT NULL,           -- iot_card | device
    resource_id          BIGINT       NOT NULL,
    iot_card_id          BIGINT,                          -- 单卡充值时有值（用于 ListOrders 查询）
    device_id            BIGINT,                          -- 设备充值时有值
    amount               BIGINT       NOT NULL,           -- 充值金额（分）
    status               SMALLINT     NOT NULL DEFAULT 1, -- 1待支付 2已支付 3已关闭 4已退款
    paid_at              TIMESTAMPTZ,
    shop_id_tag          BIGINT       NOT NULL DEFAULT 0,
    enterprise_id_tag    BIGINT,
    operator_type        VARCHAR(30)  NOT NULL,           -- personal_customer | admin_user
    generation           INT          NOT NULL DEFAULT 1,
    -- 强充专有字段（普通充值为 NULL）
    linked_package_ids   JSONB,
    linked_order_type    VARCHAR(20),
    linked_carrier_type  VARCHAR(20),
    linked_carrier_id    BIGINT,
    auto_purchase_status VARCHAR(20),                     -- pending | success | failed
    -- 累计充值（用于强充阈值判断）
    accumulated_recharge_series BIGINT NOT NULL DEFAULT 0,
    created_at           TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    updated_at           TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    deleted_at           TIMESTAMPTZ
);

-- 索引
CREATE INDEX idx_recharge_order_card      ON tb_recharge_order(iot_card_id, generation) WHERE deleted_at IS NULL;
CREATE INDEX idx_recharge_order_device    ON tb_recharge_order(device_id, generation) WHERE deleted_at IS NULL;
CREATE INDEX idx_recharge_order_user      ON tb_recharge_order(user_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_recharge_order_no        ON tb_recharge_order(recharge_order_no) WHERE deleted_at IS NULL;
CREATE INDEX idx_recharge_order_status    ON tb_recharge_order(status) WHERE deleted_at IS NULL;
