-- 创建资产分配记录表
-- 记录卡/设备在平台和代理商之间的流转历史

CREATE TABLE IF NOT EXISTS tb_asset_allocation_record (
    id BIGSERIAL PRIMARY KEY,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMPTZ,
    creator BIGINT,
    updater BIGINT,
    allocation_no VARCHAR(50) NOT NULL,
    allocation_type VARCHAR(20) NOT NULL,
    asset_type VARCHAR(20) NOT NULL,
    asset_id BIGINT NOT NULL,
    asset_identifier VARCHAR(50) NOT NULL,
    from_owner_type VARCHAR(20),
    from_owner_id BIGINT,
    to_owner_type VARCHAR(20) NOT NULL,
    to_owner_id BIGINT NOT NULL,
    related_device_id BIGINT,
    related_card_ids JSONB,
    operator_id BIGINT NOT NULL,
    remark TEXT
);

-- 创建索引（非唯一，同批次多条记录共用相同单号）
CREATE INDEX IF NOT EXISTS idx_asset_allocation_record_allocation_no ON tb_asset_allocation_record(allocation_no);
CREATE INDEX IF NOT EXISTS idx_asset_allocation_record_allocation_type ON tb_asset_allocation_record(allocation_type);
CREATE INDEX IF NOT EXISTS idx_asset_allocation_record_asset_type ON tb_asset_allocation_record(asset_type);
CREATE INDEX IF NOT EXISTS idx_asset_allocation_record_asset_id ON tb_asset_allocation_record(asset_id);
CREATE INDEX IF NOT EXISTS idx_asset_allocation_record_deleted_at ON tb_asset_allocation_record(deleted_at);

-- 添加表注释
COMMENT ON TABLE tb_asset_allocation_record IS '资产分配记录表';
COMMENT ON COLUMN tb_asset_allocation_record.allocation_no IS '分配单号（同批次相同）';
COMMENT ON COLUMN tb_asset_allocation_record.allocation_type IS '分配类型 allocate=分配 recall=回收';
COMMENT ON COLUMN tb_asset_allocation_record.asset_type IS '资产类型 iot_card=物联网卡 device=设备';
COMMENT ON COLUMN tb_asset_allocation_record.asset_id IS '资产ID';
COMMENT ON COLUMN tb_asset_allocation_record.asset_identifier IS '资产标识符（ICCID或设备号）';
COMMENT ON COLUMN tb_asset_allocation_record.from_owner_type IS '来源所有者类型 platform=平台 shop=店铺';
COMMENT ON COLUMN tb_asset_allocation_record.from_owner_id IS '来源所有者ID';
COMMENT ON COLUMN tb_asset_allocation_record.to_owner_type IS '目标所有者类型 platform=平台 shop=店铺';
COMMENT ON COLUMN tb_asset_allocation_record.to_owner_id IS '目标所有者ID';
COMMENT ON COLUMN tb_asset_allocation_record.related_device_id IS '关联设备ID（设备分配时使用）';
COMMENT ON COLUMN tb_asset_allocation_record.related_card_ids IS '关联卡ID列表（设备分配时使用）';
COMMENT ON COLUMN tb_asset_allocation_record.operator_id IS '操作人ID';
COMMENT ON COLUMN tb_asset_allocation_record.remark IS '备注';
