-- Clerk JWT 인증을 위한 RLS 정책 업데이트

-- Clerk 사용자 ID 추출 함수 생성 (public 스키마에)
CREATE OR REPLACE FUNCTION public.get_clerk_user_id() 
RETURNS TEXT AS $$
  SELECT COALESCE(
    current_setting('request.jwt.claims', true)::json->>'sub',
    (current_setting('request.jwt.claims', true)::json->'raw_user_meta_data'->>'sub')::text
  );
$$ LANGUAGE SQL STABLE SECURITY DEFINER;

-- 기존 RLS 정책 제거
DROP POLICY IF EXISTS "사용자는 자신의 프로필만 조회 가능" ON user_profiles;
DROP POLICY IF EXISTS "사용자는 자신의 프로필만 수정 가능" ON user_profiles;
DROP POLICY IF EXISTS "사용자는 자신의 프로필만 삽입 가능" ON user_profiles;

DROP POLICY IF EXISTS "사용자는 자신의 거래만 조회 가능" ON transactions;
DROP POLICY IF EXISTS "사용자는 자신의 거래만 생성 가능" ON transactions;
DROP POLICY IF EXISTS "사용자는 자신의 거래만 수정 가능" ON transactions;
DROP POLICY IF EXISTS "사용자는 자신의 거래만 삭제 가능" ON transactions;

DROP POLICY IF EXISTS "사용자는 자신의 예산만 접근 가능" ON budgets;
DROP POLICY IF EXISTS "사용자는 자신의 카테고리별 예산만 접근 가능" ON category_budgets;

-- 새로운 RLS 정책 생성 (Clerk 호환)
-- 사용자 프로필 RLS
CREATE POLICY "clerk_user_profile_select" ON user_profiles
  FOR SELECT USING (
    clerk_user_id = public.get_clerk_user_id() OR 
    clerk_user_id = (auth.jwt() ->> 'sub')
  );

CREATE POLICY "clerk_user_profile_update" ON user_profiles
  FOR UPDATE USING (
    clerk_user_id = public.get_clerk_user_id() OR 
    clerk_user_id = (auth.jwt() ->> 'sub')
  );

CREATE POLICY "clerk_user_profile_insert" ON user_profiles
  FOR INSERT WITH CHECK (
    clerk_user_id = public.get_clerk_user_id() OR 
    clerk_user_id = (auth.jwt() ->> 'sub')
  );

-- 거래 RLS
CREATE POLICY "clerk_transactions_select" ON transactions
  FOR SELECT USING (
    user_id IN (
      SELECT id FROM user_profiles 
      WHERE clerk_user_id = public.get_clerk_user_id() OR 
            clerk_user_id = (auth.jwt() ->> 'sub')
    )
  );

CREATE POLICY "clerk_transactions_insert" ON transactions
  FOR INSERT WITH CHECK (
    user_id IN (
      SELECT id FROM user_profiles 
      WHERE clerk_user_id = public.get_clerk_user_id() OR 
            clerk_user_id = (auth.jwt() ->> 'sub')
    )
  );

CREATE POLICY "clerk_transactions_update" ON transactions
  FOR UPDATE USING (
    user_id IN (
      SELECT id FROM user_profiles 
      WHERE clerk_user_id = public.get_clerk_user_id() OR 
            clerk_user_id = (auth.jwt() ->> 'sub')
    )
  );

CREATE POLICY "clerk_transactions_delete" ON transactions
  FOR DELETE USING (
    user_id IN (
      SELECT id FROM user_profiles 
      WHERE clerk_user_id = public.get_clerk_user_id() OR 
            clerk_user_id = (auth.jwt() ->> 'sub')
    )
  );

-- 예산 RLS
CREATE POLICY "clerk_budgets_all" ON budgets
  FOR ALL USING (
    user_id IN (
      SELECT id FROM user_profiles 
      WHERE clerk_user_id = public.get_clerk_user_id() OR 
            clerk_user_id = (auth.jwt() ->> 'sub')
    )
  );

-- 카테고리별 예산 RLS
CREATE POLICY "clerk_category_budgets_all" ON category_budgets
  FOR ALL USING (
    user_id IN (
      SELECT id FROM user_profiles 
      WHERE clerk_user_id = public.get_clerk_user_id() OR 
            clerk_user_id = (auth.jwt() ->> 'sub')
    )
  );

-- 익명 사용자용 정책 (공개 읽기 허용)
CREATE POLICY "allow_anon_read_user_profiles" ON user_profiles
  FOR SELECT USING (true);

-- 성능 통계 테이블은 모든 사용자가 접근 가능하도록 설정
ALTER TABLE performance_stats DISABLE ROW LEVEL SECURITY;