-- =====================================================================================
-- 数据分析模块（正式RPC，主库 ml_* 口径）
-- 文件: 08_ml_analytics_rpcs_custom_report.sql
-- 主题: 自定义报表（表结构 + CRUD RPC）
-- =====================================================================================

-- 说明：
-- 1) 该脚本会创建 analytics_reports 表，用于保存报表定义（JSONB）。
-- 2) 该脚本包含基于 auth.uid() 的 RLS 策略与 SECURITY DEFINER RPC。
-- 3) 若你暂时不希望启用 RLS，可注释掉 RLS 与 POLICY 相关语句。

-- 1) 创建自定义报表定义表
CREATE TABLE IF NOT EXISTS public.analytics_reports (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    owner_user_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    title TEXT NOT NULL,
    description TEXT,
    definition JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_analytics_reports_owner_user_id ON public.analytics_reports(owner_user_id);
CREATE INDEX IF NOT EXISTS idx_analytics_reports_updated_at ON public.analytics_reports(updated_at DESC);

-- 2) RLS（可选）
ALTER TABLE public.analytics_reports ENABLE ROW LEVEL SECURITY;

DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname = 'public' AND tablename = 'analytics_reports' AND policyname = 'analytics_reports_owner_all') THEN
    CREATE POLICY analytics_reports_owner_all ON public.analytics_reports
      FOR ALL
      USING (auth.uid() = (SELECT auth_id FROM public.ak_users WHERE id = owner_user_id))
      WITH CHECK (auth.uid() = (SELECT auth_id FROM public.ak_users WHERE id = owner_user_id));
  END IF;
END $$;

-- 3) RPC：获取我的报表列表
CREATE OR REPLACE FUNCTION public.rpc_get_custom_reports()
RETURNS TABLE (
  id UUID,
  title TEXT,
  description TEXT,
  updated_at TIMESTAMPTZ
)
LANGUAGE sql
SECURITY DEFINER
AS $$
  SELECT r.id, r.title, r.description, r.updated_at
  FROM public.analytics_reports r
  WHERE r.owner_user_id = (SELECT id FROM public.ak_users WHERE auth_id = auth.uid() LIMIT 1)
  ORDER BY r.updated_at DESC;
$$;

-- 4) RPC：创建报表
CREATE OR REPLACE FUNCTION public.rpc_create_custom_report(
  p_title TEXT,
  p_description TEXT,
  p_definition JSONB
)
RETURNS UUID
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
DECLARE
  v_owner_user_id UUID;
  v_report_id UUID;
BEGIN
  SELECT id INTO v_owner_user_id
  FROM public.ak_users
  WHERE auth_id = auth.uid()
  LIMIT 1;

  IF v_owner_user_id IS NULL THEN
    RAISE EXCEPTION 'No matching ak_users row for auth.uid()';
  END IF;

  INSERT INTO public.analytics_reports (owner_user_id, title, description, definition)
  VALUES (v_owner_user_id, p_title, p_description, p_definition)
  RETURNING id INTO v_report_id;

  RETURN v_report_id;
END;
$$;

-- 5) RPC：更新报表
CREATE OR REPLACE FUNCTION public.rpc_update_custom_report(
  p_report_id UUID,
  p_title TEXT,
  p_description TEXT,
  p_definition JSONB
)
RETURNS VOID
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
DECLARE
  v_owner_user_id UUID;
BEGIN
  SELECT id INTO v_owner_user_id
  FROM public.ak_users
  WHERE auth_id = auth.uid()
  LIMIT 1;

  IF v_owner_user_id IS NULL THEN
    RAISE EXCEPTION 'No matching ak_users row for auth.uid()';
  END IF;

  UPDATE public.analytics_reports
  SET
    title = p_title,
    description = p_description,
    definition = p_definition,
    updated_at = now()
  WHERE id = p_report_id
    AND owner_user_id = v_owner_user_id;
END;
$$;

-- 6) RPC：删除报表
CREATE OR REPLACE FUNCTION public.rpc_delete_custom_report(
  p_report_id UUID
)
RETURNS VOID
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
DECLARE
  v_owner_user_id UUID;
BEGIN
  SELECT id INTO v_owner_user_id
  FROM public.ak_users
  WHERE auth_id = auth.uid()
  LIMIT 1;

  IF v_owner_user_id IS NULL THEN
    RAISE EXCEPTION 'No matching ak_users row for auth.uid()';
  END IF;

  DELETE FROM public.analytics_reports
  WHERE id = p_report_id
    AND owner_user_id = v_owner_user_id;
END;
$$;
