CREATE TABLE IF NOT EXISTS tb_asset_package_batch_order_task (
    id bigserial PRIMARY KEY,
    task_no varchar(50) NOT NULL,
    package_id bigint NOT NULL,
    package_code varchar(100) NOT NULL DEFAULT '',
    package_name varchar(255) NOT NULL DEFAULT '',
    payment_method varchar(20) NOT NULL,
    file_name varchar(255) NOT NULL DEFAULT '',
    storage_key varchar(500) NOT NULL,
    voucher_keys jsonb NOT NULL DEFAULT '[]'::jsonb,
    status integer NOT NULL DEFAULT 1,
    total_count integer NOT NULL DEFAULT 0,
    success_count integer NOT NULL DEFAULT 0,
    fail_count integer NOT NULL DEFAULT 0,
    result_items jsonb NOT NULL DEFAULT '[]'::jsonb,
    error_message text NOT NULL DEFAULT '',
    creator_user_type integer NOT NULL DEFAULT 0,
    creator_shop_id bigint NOT NULL DEFAULT 0,
    creator_name varchar(100) NOT NULL DEFAULT '',
    started_at timestamptz,
    completed_at timestamptz,
    creator bigint NOT NULL DEFAULT 0,
    updater bigint NOT NULL DEFAULT 0,
    created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at timestamptz,
    CONSTRAINT chk_asset_package_batch_order_status CHECK (status IN (1, 2, 3, 4, 5)),
    CONSTRAINT chk_asset_package_batch_order_payment_method CHECK (payment_method IN ('wallet', 'offline')),
    CONSTRAINT chk_asset_package_batch_order_counts CHECK (
        total_count >= 0 AND success_count >= 0 AND fail_count >= 0
        AND success_count + fail_count <= total_count
    )
);

CREATE UNIQUE INDEX IF NOT EXISTS uq_asset_package_batch_order_task_no
    ON tb_asset_package_batch_order_task (task_no)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_asset_package_batch_order_status_created
    ON tb_asset_package_batch_order_task (status, created_at DESC)
    WHERE deleted_at IS NULL;

COMMENT ON TABLE tb_asset_package_batch_order_task IS '单列CSV资产套餐批量订购任务';
COMMENT ON COLUMN tb_asset_package_batch_order_task.package_id IS '整批统一套餐ID';
COMMENT ON COLUMN tb_asset_package_batch_order_task.payment_method IS '整批统一支付方式(wallet/offline)';
COMMENT ON COLUMN tb_asset_package_batch_order_task.storage_key IS '源CSV对象存储Key';
COMMENT ON COLUMN tb_asset_package_batch_order_task.voucher_keys IS '线下支付凭证对象存储Key列表';
COMMENT ON COLUMN tb_asset_package_batch_order_task.status IS '任务状态(1待处理,2处理中,3已完成,4已失败,5已取消)';
COMMENT ON COLUMN tb_asset_package_batch_order_task.result_items IS '逐行成功或失败结果明细';
