-- B端商户档案表
CREATE TABLE public.tenant_profiles (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL UNIQUE,
  company_name TEXT,
  first_natural_input TEXT,
  inferred_problem_type TEXT,
  first_task_completed BOOLEAN DEFAULT false,
  onboarding_completed_at TIMESTAMPTZ,
  context_snapshot JSONB DEFAULT '{}',
  metadata JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

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

-- RLS 策略：用户只能查看和编辑自己的档案
CREATE POLICY "Users can view own tenant profile"
ON public.tenant_profiles
FOR SELECT
TO authenticated
USING (auth.uid() = user_id);

CREATE POLICY "Users can insert own tenant profile"
ON public.tenant_profiles
FOR INSERT
TO authenticated
WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can update own tenant profile"
ON public.tenant_profiles
FOR UPDATE
TO authenticated
USING (auth.uid() = user_id);

-- 管理员可以查看所有档案
CREATE POLICY "Admins can view all tenant profiles"
ON public.tenant_profiles
FOR SELECT
TO authenticated
USING (public.is_admin(auth.uid()));

-- 自动更新 updated_at
CREATE TRIGGER update_tenant_profiles_updated_at
  BEFORE UPDATE ON public.tenant_profiles
  FOR EACH ROW
  EXECUTE FUNCTION public.update_updated_at_column();