-- 回滚：恢复 ShopSeriesAllocation 层

-- ============================================
-- 1. 重建 ShopSeriesAllocation 表
-- ============================================

CREATE TABLE IF NOT EXISTS tb_shop_series_allocation (
    id BIGSERIAL PRIMARY KEY,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    deleted_at TIMESTAMPTZ,
    creator BIGINT NOT NULL DEFAULT 0,
    updater BIGINT NOT NULL DEFAULT 0,
    shop_id BIGINT NOT NULL,
    series_id BIGINT NOT NULL,
    allocator_shop_id BIGINT NOT NULL DEFAULT 0,
    cost_price_markup BIGINT NOT NULL DEFAULT 0,
    one_time_commission_amount BIGINT NOT NULL DEFAULT 0,
    status INTEGER NOT NULL DEFAULT 1
);

COMMENT ON TABLE tb_shop_series_allocation IS '店铺系列分配表';
COMMENT ON COLUMN tb_shop_series_allocation.shop_id IS '被分配店铺ID';
COMMENT ON COLUMN tb_shop_series_allocation.series_id IS '套餐系列ID';
COMMENT ON COLUMN tb_shop_series_allocation.allocator_shop_id IS '分配者店铺ID（0表示平台分配）';
COMMENT ON COLUMN tb_shop_series_allocation.cost_price_markup IS '成本价加价（分）';
COMMENT ON COLUMN tb_shop_series_allocation.one_time_commission_amount IS '一次性佣金金额（分）';

CREATE INDEX IF NOT EXISTS idx_shop_series_allocation_shop_id ON tb_shop_series_allocation(shop_id);
CREATE INDEX IF NOT EXISTS idx_shop_series_allocation_series_id ON tb_shop_series_allocation(series_id);

-- ============================================
-- 2. 重建 ShopSeriesAllocationConfig 表
-- ============================================

CREATE TABLE IF NOT EXISTS tb_shop_series_allocation_config (
    id BIGSERIAL PRIMARY KEY,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    deleted_at TIMESTAMPTZ,
    creator BIGINT NOT NULL DEFAULT 0,
    updater BIGINT NOT NULL DEFAULT 0,
    allocation_id BIGINT NOT NULL,
    config_type VARCHAR(50) NOT NULL,
    config_value JSONB
);

COMMENT ON TABLE tb_shop_series_allocation_config IS '店铺系列分配配置表';

-- ============================================
-- 3. 恢复 allocation_id 字段
-- ============================================

ALTER TABLE tb_shop_package_allocation
ADD COLUMN IF NOT EXISTS allocation_id BIGINT NOT NULL DEFAULT 0;

-- ============================================
-- 4. 删除新增的字段
-- ============================================

DROP INDEX IF EXISTS idx_shop_package_allocation_series_id;
DROP INDEX IF EXISTS idx_shop_package_allocation_allocator_shop_id;

ALTER TABLE tb_shop_package_allocation
DROP COLUMN IF EXISTS series_id;

ALTER TABLE tb_shop_package_allocation
DROP COLUMN IF EXISTS allocator_shop_id;
