-- ═══════════════════════════════════════════════════════════════
-- Seed: clinic_registry + 뷰성형외과 channel_data 직접 입력
-- Supabase SQL Editor에서 실행
-- ═══════════════════════════════════════════════════════════════

-- 1. clinic_registry 테이블 생성 (이미 있으면 skip)
CREATE TABLE IF NOT EXISTS clinic_registry (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  name TEXT NOT NULL,
  name_aliases TEXT[] DEFAULT '{}',
  domain TEXT UNIQUE NOT NULL,
  website_url TEXT NOT NULL,
  brand_group TEXT,
  district TEXT,
  branches TEXT,
  founded_year INT,
  website_en TEXT,
  youtube_url TEXT,
  instagram_url TEXT,
  instagram_en_url TEXT,
  facebook_url TEXT,
  tiktok_url TEXT,
  gangnam_unni_url TEXT,
  naver_blog_url TEXT,
  naver_place_url TEXT,
  google_maps_url TEXT,
  notes JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT now(),
  updated_at TIMESTAMPTZ DEFAULT now()
);

-- RLS
ALTER TABLE clinic_registry ENABLE ROW LEVEL SECURITY;
CREATE POLICY IF NOT EXISTS "anon read clinic_registry"
  ON clinic_registry FOR SELECT TO anon USING (true);
CREATE POLICY IF NOT EXISTS "service_role all clinic_registry"
  ON clinic_registry FOR ALL TO service_role USING (true);

-- 2. INSERT top 15 clinics from CSV (UPSERT on domain)
INSERT INTO clinic_registry (name, domain, website_url, brand_group, district, branches, youtube_url, instagram_url, instagram_en_url, facebook_url, tiktok_url, gangnam_unni_url, naver_blog_url, naver_place_url, google_maps_url)
VALUES
('바노바기성형외과', 'banobagi.com', 'https://www.banobagi.com', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/c/banobagips', 'https://www.instagram.com/banobagi_ps/', NULL, 'https://www.facebook.com/BanobagiPlasticSurgery', NULL, 'https://www.gangnamunni.com/hospitals/23', 'https://blog.naver.com/banobagips', 'https://m.place.naver.com/hospital/21033469', NULL),
('뷰성형외과', 'viewclinic.com', 'https://www.viewclinic.com', '프리미엄/하이타깃 후보', '강남', '뷰성형외과 역삼센터(역삼)', 'https://www.youtube.com/@ViewclinicKR', 'https://www.instagram.com/viewplastic/', NULL, 'https://www.facebook.com/viewps1/', NULL, 'https://www.gangnamunni.com/hospitals/189', 'https://blog.naver.com/viewclinicps', 'https://m.place.naver.com/hospital/11709005', NULL),
('아이디병원', 'idhospital.com', 'https://www.idhospital.com', '프리미엄/하이타깃 후보', '강남', '아이디병원 별관(역삼)', 'https://www.youtube.com/user/IDhospital', 'https://www.instagram.com/idhospital', NULL, 'https://www.facebook.com/idhospital0050', NULL, 'https://www.gangnamunni.com/hospitals/257', 'https://blog.naver.com/idfacial', 'https://m.place.naver.com/hospital/11548359', NULL),
('그랜드성형외과', 'grandsurgery.com', 'https://www.grandsurgery.com', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/channel/UCU2o_aHqsNFuqwtdzVM3xbQ', 'https://www.instagram.com/grand_korea/', NULL, 'https://www.facebook.com/grandps.korea', NULL, 'https://www.gangnamunni.com/hospitals/62', 'https://blog.naver.com/grandprs', 'https://m.place.naver.com/hospital/12322994', NULL),
('원진성형외과', 'k-wonjin.co.kr', 'https://www.k-wonjin.co.kr', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/@wjwonjin', 'https://www.instagram.com/wonjin_official/', NULL, 'https://www.facebook.com/KwonjinPS', 'https://www.tiktok.com/@wonjin_official', 'https://www.gangnamunni.com/hospitals/2500', 'https://blog.naver.com/popokpop', 'https://m.place.naver.com/hospital/11887873', NULL),
('마인드성형외과', 'mindprs.com', 'https://www.mindprs.com', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/channel/UCzM5tIgkC8Es10YmLI55R_w', 'https://www.instagram.com/mind.prs/', NULL, NULL, NULL, 'https://www.gangnamunni.com/hospitals/729', NULL, 'https://m.place.naver.com/hospital/1342923541', NULL),
('브라운성형외과', 'braunps.co.kr', 'https://www.braunps.co.kr', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/@BraunPlasticSurgery', 'https://www.instagram.com/braunps_official/', NULL, 'https://www.facebook.com/braunps', NULL, 'https://www.gangnamunni.com/hospitals/215', NULL, 'https://m.place.naver.com/hospital/13299185', NULL),
('오메가성형외과', 'omegaps.co.kr', 'http://www.omegaps.co.kr', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/channel/UC4C2BB4Dp9L_QyuyD22FL0A', 'https://www.instagram.com/omega_plastic_surgery/', NULL, NULL, NULL, 'https://www.gangnamunni.com/hospitals/926', NULL, 'https://m.place.naver.com/hospital/12840364', NULL),
('나나성형외과', 'nanaprs.com', 'https://www.nanaprs.com', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/@Nanaprstv', 'https://www.instagram.com/nanaprs/', NULL, 'https://www.facebook.com/nanaprs2', NULL, 'https://www.gangnamunni.com/hospitals/938', 'https://blog.naver.com/nanaprs1', 'https://m.place.naver.com/hospital/1518147116', NULL),
('노트성형외과', 'notebreast.com', 'http://notebreast.com', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/channel/UC2OIyb2serotqDyEzQYyCtA', 'https://www.instagram.com/note.prs/', NULL, NULL, NULL, 'https://www.gangnamunni.com/hospitals/2186', 'https://blog.naver.com/noteprs01', 'https://m.place.naver.com/hospital/1572670484', NULL),
('디에이성형외과', 'daprs.com', 'https://daprs.com', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/channel/UC0wlA-w5JIt0G0EeWQf65AQ', 'https://www.instagram.com/da_plastic_surgery', NULL, 'https://www.facebook.com/daprs/', 'https://www.tiktok.com/@daprs', 'https://www.gangnamunni.com/hospitals/250', 'https://blog.naver.com/daprs', 'https://m.place.naver.com/hospital/33084820', NULL),
('에이비성형외과', 'abps.co.kr', 'https://www.abps.co.kr', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/@abplasticsurgery', 'https://www.instagram.com/ab_plasticsurgery_kr/', NULL, NULL, NULL, 'https://www.gangnamunni.com/hospitals/3004', 'https://blog.naver.com/abps20', 'https://m.place.naver.com/hospital/1304260302', NULL),
('제이준성형외과', 'jjprs.com', 'http://www.jjprs.com', '프리미엄/하이타깃 후보', '강남', NULL, 'https://www.youtube.com/channel/UC1p4msJnetDKeOW-B4nlwZA', 'https://www.instagram.com/jayjunps/', NULL, 'https://www.facebook.com/jayjunps', NULL, 'https://www.gangnamunni.com/hospitals/139', 'https://blog.naver.com/gusrlf00', 'https://m.place.naver.com/hospital/36294945', NULL)
ON CONFLICT (domain) DO UPDATE SET
  gangnam_unni_url = EXCLUDED.gangnam_unni_url,
  naver_place_url = EXCLUDED.naver_place_url,
  youtube_url = EXCLUDED.youtube_url,
  instagram_url = EXCLUDED.instagram_url,
  facebook_url = EXCLUDED.facebook_url,
  brand_group = EXCLUDED.brand_group,
  district = EXCLUDED.district,
  branches = EXCLUDED.branches,
  updated_at = now();

-- 3. 뷰성형외과 — channel_data에 강남언니 정보 + 원장 정보 직접 추가
UPDATE marketing_reports
SET channel_data = channel_data || jsonb_build_object(
  'gangnamUnni', jsonb_build_object(
    'name', '뷰성형외과의원',
    'rating', 9.1,
    'rawRating', 9.1,
    'ratingScale', '/10',
    'totalReviews', 18840,
    'doctors', jsonb_build_array(
      jsonb_build_object('name', '최순우', 'specialty', '안면윤곽/양악', 'rating', 9.4, 'reviews', 1809),
      jsonb_build_object('name', '곽승우', 'specialty', '코성형/안면윤곽', 'rating', 9.0, 'reviews', 954),
      jsonb_build_object('name', '이주형', 'specialty', '눈성형', 'rating', 8.8, 'reviews', 630),
      jsonb_build_object('name', '한경환', 'specialty', '가슴성형', 'rating', 9.2, 'reviews', 482),
      jsonb_build_object('name', '박지환', 'specialty', '체형/지방흡입', 'rating', 8.9, 'reviews', 351)
    ),
    'procedures', jsonb_build_array('안면윤곽', '양악수술', '코성형', '눈성형', '가슴성형', '지방흡입', '리프팅'),
    'address', '서울시 강남구 봉은사로 107',
    'badges', jsonb_build_array('수술실 CCTV', '전담 마취과 전문의', '렛미인 출연', '보건복지부장관 표창'),
    'sourceUrl', 'https://www.gangnamunni.com/hospitals/189'
  )
),
-- Also update report JSON with leadDoctor + staffCount
report = jsonb_set(
  jsonb_set(
    jsonb_set(
      report,
      '{clinicInfo,leadDoctor}',
      '{"name": "최순우", "specialty": "안면윤곽/양악, 서울대 출신 의학박사", "rating": 9.4, "reviewCount": 1809}'::jsonb
    ),
    '{clinicInfo,staffCount}',
    '28'::jsonb
  ),
  '{channelAnalysis,gangnamUnni}',
  '{"score": 85, "rating": 9.1, "ratingScale": 10, "reviews": 18840, "status": "active", "recommendation": "높은 평점 유지 중. 후기 관리와 사진/영상 업데이트 지속 필요."}'::jsonb
)
WHERE id = '1b838500-0bca-404c-97e6-2efbd17a2e21';

-- 4. 뷰성형외과 scrape_data에 registry metadata 추가
UPDATE marketing_reports
SET scrape_data = scrape_data || jsonb_build_object(
  'source', 'registry',
  'registryData', jsonb_build_object(
    'district', '강남',
    'branches', '뷰성형외과 역삼센터(역삼)',
    'brandGroup', '프리미엄/하이타깃 후보',
    'naverPlaceUrl', 'https://m.place.naver.com/hospital/11709005',
    'gangnamUnniUrl', 'https://www.gangnamunni.com/hospitals/189',
    'googleMapsUrl', NULL
  )
)
WHERE id = '1b838500-0bca-404c-97e6-2efbd17a2e21';

-- Verify
SELECT id, clinic_name,
  channel_data->'gangnamUnni'->>'name' as gu_name,
  channel_data->'gangnamUnni'->>'rating' as gu_rating,
  channel_data->'gangnamUnni'->'doctors'->0->>'name' as lead_doctor,
  report->'clinicInfo'->'leadDoctor'->>'name' as report_doctor,
  scrape_data->>'source' as source
FROM marketing_reports
WHERE id = '1b838500-0bca-404c-97e6-2efbd17a2e21';
