-- 佣金流水表：记录每一笔佣金变动（冻结/可用/已提现/取消）
CREATE TABLE IF NOT EXISTS public.ak_commission_logs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- 佣金获得者
  uid UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
  -- 佣金来源用户（下单用户/被推广用户，可为空）
  source_uid UUID REFERENCES public.ak_users(id) ON DELETE SET NULL,

  -- 关联订单
  order_id UUID REFERENCES public.ml_orders(id) ON DELETE SET NULL,
  order_no VARCHAR(50),

  -- 金额与状态
  amount DECIMAL(12,2) NOT NULL DEFAULT 0,
  status TEXT NOT NULL DEFAULT 'frozen', -- frozen/available/withdrawn/canceled

  -- 冻结到期时间（用于解冻逻辑）
  frozen_until TIMESTAMPTZ,

  remark TEXT,

  created_at TIMESTAMPTZ DEFAULT now(),
  updated_at TIMESTAMPTZ DEFAULT now(),

  CONSTRAINT chk_ak_commission_amount_nonneg CHECK (amount >= 0),
  CONSTRAINT chk_ak_commission_status CHECK (status IN ('frozen','available','withdrawn','canceled'))
);

CREATE INDEX IF NOT EXISTS idx_ak_commission_logs_uid ON public.ak_commission_logs(uid);
CREATE INDEX IF NOT EXISTS idx_ak_commission_logs_order_id ON public.ak_commission_logs(order_id);
CREATE INDEX IF NOT EXISTS idx_ak_commission_logs_status ON public.ak_commission_logs(status);
CREATE INDEX IF NOT EXISTS idx_ak_commission_logs_created_at ON public.ak_commission_logs(created_at);

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

-- Admin 可读写
CREATE POLICY "Admins can manage commission logs"
ON public.ak_commission_logs
FOR ALL
TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM public.ak_users
    WHERE id = auth.uid() AND role = 'admin'
  )
)
WITH CHECK (
  EXISTS (
    SELECT 1 FROM public.ak_users
    WHERE id = auth.uid() AND role = 'admin'
  )
);

-- 用户仅可查看自己的佣金流水
CREATE POLICY "Users can view own commission logs"
ON public.ak_commission_logs
FOR SELECT
TO authenticated
USING (uid = auth.uid());
