-- =====================================================================================
-- Schema: 充值配置与额度模板表
-- 位置：docs/sql/10_schema/marketing/ak_recharge_management_v1.sql
-- 说明：管理用户充值开关、最低金额及预设额度，按商家隔离。
-- =====================================================================================

-- 1. 充值基础配置表 (每个商家一条记录)
CREATE TABLE IF NOT EXISTS public.ak_recharge_configs (
    id TEXT PRIMARY KEY DEFAULT 'recharge_config',
    merchant_id UUID NOT NULL UNIQUE REFERENCES public.ak_users(id) ON DELETE CASCADE,
    
    balance_enabled BOOLEAN DEFAULT true,        -- 余额功能是否启用
    recharge_notice TEXT,                        -- 充值注意事项说明
    mp_recharge_enabled BOOLEAN DEFAULT false,   -- 小程序充值开关
    min_recharge_amount DECIMAL(12,2) DEFAULT 0.01, -- 最低充值金额
    
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- 2. 充值额度模板表
CREATE TABLE IF NOT EXISTS public.ak_recharge_quotas (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    merchant_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    
    price DECIMAL(12,2) NOT NULL DEFAULT 0,      -- 售价（实际充值金额）
    bonus_price DECIMAL(12,2) NOT NULL DEFAULT 0, -- 赠送金额
    
    is_open BOOLEAN DEFAULT true,                -- 是否可用
    sort_order INTEGER DEFAULT 0,                -- 排序
    
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- 3. 启用 RLS
ALTER TABLE public.ak_recharge_configs ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ak_recharge_quotas ENABLE ROW LEVEL SECURITY;

-- 4. 创建权限策略 (按 merchant_id 隔离)
CREATE POLICY "Merchants manage their own recharge configs" ON public.ak_recharge_configs FOR ALL TO authenticated USING (merchant_id = auth.uid()) WITH CHECK (merchant_id = auth.uid());
CREATE POLICY "Merchants manage their own recharge quotas" ON public.ak_recharge_quotas FOR ALL TO authenticated USING (merchant_id = auth.uid()) WITH CHECK (merchant_id = auth.uid());

-- 允许所有认证用户查看
CREATE POLICY "Users can view recharge configs" ON public.ak_recharge_configs FOR SELECT TO authenticated USING (true);
CREATE POLICY "Users can view active recharge quotas" ON public.ak_recharge_quotas FOR SELECT TO authenticated USING (is_open = true);

-- 5. 索引
CREATE INDEX IF NOT EXISTS idx_recharge_quotas_merchant ON public.ak_recharge_quotas(merchant_id);
