-- =====================================================================================
-- Schema: 商品会员价表 (按 SKU + 等级 维度)
-- 位置：docs/sql/10_schema/product/ak_product_member_prices_v1.sql
-- 对象类型：Schema (DDL)
-- 版本：v1
-- 说明：记录特定商品 SKU 在不同会员等级下的专享价格，按商家隔离。
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_product_member_prices (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    merchant_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    product_id UUID NOT NULL REFERENCES public.ml_products(id) ON DELETE CASCADE,
    sku_id UUID NOT NULL REFERENCES public.ml_product_skus(id) ON DELETE CASCADE,
    level_id UUID NOT NULL REFERENCES public.ak_user_levels(id) ON DELETE CASCADE,
    
    member_price DECIMAL(12,2) NOT NULL CHECK (member_price >= 0),
    
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now(),

    -- 约束：同一个商家的同一个 SKU 在同一个等级下只能有一个会员价
    UNIQUE(merchant_id, sku_id, level_id)
);

-- 索引
CREATE INDEX IF NOT EXISTS idx_prod_member_prices_product ON public.ak_product_member_prices(product_id);
CREATE INDEX IF NOT EXISTS idx_prod_member_prices_sku ON public.ak_product_member_prices(sku_id);
CREATE INDEX IF NOT EXISTS idx_prod_member_prices_level ON public.ak_product_member_prices(level_id);
CREATE INDEX IF NOT EXISTS idx_prod_member_prices_merchant ON public.ak_product_member_prices(merchant_id);

-- 启用 RLS
ALTER TABLE public.ak_product_member_prices ENABLE ROW LEVEL SECURITY;

-- 权限策略：商家仅能管理自己的商品会员价
CREATE POLICY "Merchants can manage their own product member prices"
ON public.ak_product_member_prices
FOR ALL
TO authenticated
USING (merchant_id = auth.uid())
WITH CHECK (merchant_id = auth.uid());

-- 允许所有认证用户查看会员价（前台下单需计算）
CREATE POLICY "Authenticated users can view product member prices"
ON public.ak_product_member_prices
FOR SELECT
TO authenticated
USING (true);
