-- =====================================================================================
-- Schema: 运费模板表
-- 位置：docs/sql/10_schema/product/ak_shipping_templates_v1.sql
-- 说明：管理商家的运费计算规则，按商家隔离。
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_shipping_templates (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    merchant_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    
    name TEXT NOT NULL,                          -- 模板名称
    calc_method TEXT DEFAULT 'piece',            -- 计费方式: piece(件数), weight(重量), volume(体积)
    is_free_shipping BOOLEAN DEFAULT false,      -- 是否包邮
    
    sort_order INTEGER DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

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

-- 权限策略：商家管理自己的模板
CREATE POLICY "Merchants manage own shipping templates" 
ON public.ak_shipping_templates FOR ALL 
TO authenticated
USING (merchant_id = auth.uid())
WITH CHECK (merchant_id = auth.uid());

-- 允许查看
CREATE POLICY "Authenticated users view shipping templates" 
ON public.ak_shipping_templates FOR SELECT 
TO authenticated
USING (true);

-- 索引
CREATE INDEX IF NOT EXISTS idx_shipping_templates_merchant ON public.ak_shipping_templates(merchant_id);
