-- =============================================
-- Analytics Dashboard 专用：订单表 RLS 策略补充
-- 目标：
--   - 允许角色为 admin / analytics 的用户在 Supabase 中
--     通过 RPC 查询全量订单与订单明细（仅用于统计分析）。
--   - 不影响普通消费者的订单隔离策略。
-- 依赖：
--   - public.ak_users 表存在，且包含字段：id(uuid), role(text)
--   - 01_create_tables.sql 已经启用 orders / order_items 的 RLS
-- =============================================

DO $$
BEGIN
  -- 如果 ak_users 表不存在，直接跳过（避免报错）
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = 'public' AND table_name = 'ak_users'
  ) THEN
    RAISE NOTICE 'ak_users table not found, skip analytics RLS policies for orders.';
    RETURN;
  END IF;

  -- orders：允许 admin / analytics 角色读取全量订单用于分析
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies
    WHERE schemaname = 'public'
      AND tablename = 'orders'
      AND policyname = 'analytics_can_select_all_orders'
  ) THEN
    EXECUTE $pol$
      CREATE POLICY analytics_can_select_all_orders
      ON public.orders
      FOR SELECT
      USING (
        auth.role() = 'authenticated'
        AND EXISTS (
          SELECT 1 FROM public.ak_users u
          WHERE u.id = auth.uid()
            AND u.role IN ('admin','analytics')
        )
      )
    $pol$;
  END IF;

  -- order_items：允许 admin / analytics 查看任意订单的明细
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies
    WHERE schemaname = 'public'
      AND tablename = 'order_items'
      AND policyname = 'analytics_can_select_all_order_items'
  ) THEN
    EXECUTE $pol$
      CREATE POLICY analytics_can_select_all_order_items
      ON public.order_items
      FOR SELECT
      USING (
        auth.role() = 'authenticated'
        AND EXISTS (
          SELECT 1 FROM public.ak_users u
          WHERE u.id = auth.uid()
            AND u.role IN ('admin','analytics')
        )
      )
    $pol$;
  END IF;
END;
$$;

SELECT 'orders analytics RLS policies applied' AS message;

