-- 2026-04-30: 인수용 RLS 강화
-- 정책 요약:
--   * 모든 콘텐츠 테이블: anon = SELECT(read) only
--   * inquiries / reviews: anon = INSERT 허용 (방문자 문의/후기 등록)
--   * UPDATE/DELETE: service_role 만 (admin 페이지가 service_role 키로 호출)
--
-- 주의: 이 SQL을 적용하면 anon 키로 직접 INSERT/UPDATE 하던 admin 코드는
--       service_role 키를 사용하도록 환경변수를 분리해야 함.
--       현재 admin은 PW 검증 후 anon 키로 RPC 호출 — 추후 인수 시점에 service_role 분리.

-- ============================================================
-- 1. 모든 테이블 RLS enable
-- ============================================================
alter table cms_config enable row level security;
alter table notices enable row level security;
alter table products enable row level security;
alter table qna enable row level security;
alter table inquiries enable row level security;
alter table reviews enable row level security;
alter table external_links enable row level security;

-- ============================================================
-- 2. anon SELECT (사이트 표시용)
-- ============================================================
do $$
declare t text;
begin
  for t in select unnest(array['cms_config','notices','products','qna','external_links','reviews']) loop
    if not exists (
      select 1 from pg_policies where schemaname = 'public' and tablename = t and policyname = (t || '_anon_read')
    ) then
      execute format('create policy "%I" on public.%I for select to anon, authenticated using (true)', t || '_anon_read', t);
    end if;
  end loop;
end$$;

-- inquiries는 일반 read 차단(개인정보) — admin만 접근
do $$
begin
  if not exists (
    select 1 from pg_policies where schemaname = 'public' and tablename = 'inquiries' and policyname = 'inquiries_admin_read_only'
  ) then
    create policy "inquiries_admin_read_only" on public.inquiries for select to authenticated using (true);
  end if;
end$$;

-- ============================================================
-- 3. anon INSERT — inquiries / reviews (방문자가 직접 등록)
-- ============================================================
do $$
begin
  if not exists (
    select 1 from pg_policies where schemaname = 'public' and tablename = 'inquiries' and policyname = 'inquiries_anon_insert'
  ) then
    create policy "inquiries_anon_insert" on public.inquiries for insert to anon with check (true);
  end if;
  if not exists (
    select 1 from pg_policies where schemaname = 'public' and tablename = 'reviews' and policyname = 'reviews_anon_insert'
  ) then
    create policy "reviews_anon_insert" on public.reviews for insert to anon with check (true);
  end if;
end$$;

-- ============================================================
-- NOTE: UPDATE/DELETE 정책은 service_role 자동 우회(RLS bypass).
--        admin은 service_role 키 사용을 권장 — 별도 마이그레이션에서 분리.
-- ============================================================
