-- ============================================
-- 축제-펜션 연동 테이블 마이그레이션
-- 버전: 1.0
-- 날짜: 2024-12-08
-- ============================================

-- 축제 테이블
CREATE TABLE IF NOT EXISTS festivals (
  id INTEGER PRIMARY KEY AUTOINCREMENT,

  -- TourAPI 식별자
  content_id TEXT UNIQUE NOT NULL,
  content_type_id TEXT DEFAULT '15',

  -- 기본 정보
  title TEXT NOT NULL,
  overview TEXT,

  -- 주소 정보
  addr1 TEXT,
  addr2 TEXT,
  zipcode TEXT,

  -- 지역 코드
  area_code TEXT,
  sigungu_code TEXT,
  sido TEXT,
  sigungu TEXT,

  -- 좌표
  mapx REAL,
  mapy REAL,

  -- 기간
  event_start_date TEXT,
  event_end_date TEXT,

  -- 이미지
  first_image TEXT,
  first_image2 TEXT,

  -- 연락처
  tel TEXT,
  homepage TEXT,

  -- 상세 정보
  place TEXT,
  place_info TEXT,
  play_time TEXT,
  program TEXT,
  use_fee TEXT,
  age_limit TEXT,

  -- 주최/주관
  sponsor1 TEXT,
  sponsor1_tel TEXT,
  sponsor2 TEXT,
  sponsor2_tel TEXT,

  -- 부대정보
  sub_event TEXT,
  booking_place TEXT,

  -- 시스템
  is_active INTEGER DEFAULT 1,
  view_count INTEGER DEFAULT 0,
  last_synced_at TEXT,
  created_at TEXT DEFAULT CURRENT_TIMESTAMP,
  updated_at TEXT DEFAULT CURRENT_TIMESTAMP
);

-- 인덱스
CREATE INDEX IF NOT EXISTS idx_festivals_area ON festivals(area_code, sigungu_code);
CREATE INDEX IF NOT EXISTS idx_festivals_date ON festivals(event_start_date, event_end_date);
CREATE INDEX IF NOT EXISTS idx_festivals_coords ON festivals(mapx, mapy);
CREATE INDEX IF NOT EXISTS idx_festivals_active ON festivals(is_active, event_end_date);


-- 전국 펜션 마스터 테이블
CREATE TABLE IF NOT EXISTS public_pensions (
  id INTEGER PRIMARY KEY AUTOINCREMENT,

  -- 데이터 출처
  source TEXT NOT NULL,
  source_id TEXT,
  content_id TEXT,

  -- 기본 정보
  name TEXT NOT NULL,
  name_normalized TEXT,

  -- 주소 정보
  address TEXT,
  road_address TEXT,
  jibun_address TEXT,
  zipcode TEXT,

  -- 지역 코드
  sido TEXT,
  sigungu TEXT,
  eupmyeondong TEXT,
  area_code TEXT,
  sigungu_code TEXT,

  -- 좌표
  mapx REAL,
  mapy REAL,

  -- 연락처
  tel TEXT,
  homepage TEXT,

  -- 이미지
  thumbnail TEXT,
  images TEXT,

  -- 숙박 상세
  checkin_time TEXT,
  checkout_time TEXT,
  room_count INTEGER,
  room_type TEXT,
  facilities TEXT,
  parking TEXT,
  reservation_url TEXT,

  -- 특성
  pet_allowed INTEGER DEFAULT 0,
  pickup_available INTEGER DEFAULT 0,
  cooking_available INTEGER DEFAULT 0,
  barbecue_available INTEGER DEFAULT 0,

  -- 영업 상태
  business_status TEXT DEFAULT '영업중',
  license_date TEXT,
  closure_date TEXT,

  -- 소유권
  is_verified INTEGER DEFAULT 0,
  is_claimed INTEGER DEFAULT 0,
  claimed_by INTEGER,
  claimed_at TEXT,

  -- 통계
  view_count INTEGER DEFAULT 0,

  -- 타임스탬프
  last_synced_at TEXT,
  created_at TEXT DEFAULT CURRENT_TIMESTAMP,
  updated_at TEXT DEFAULT CURRENT_TIMESTAMP,

  FOREIGN KEY (claimed_by) REFERENCES users(id)
);

-- 인덱스
CREATE INDEX IF NOT EXISTS idx_public_pensions_sido ON public_pensions(sido);
CREATE INDEX IF NOT EXISTS idx_public_pensions_sigungu ON public_pensions(sido, sigungu);
CREATE INDEX IF NOT EXISTS idx_public_pensions_coords ON public_pensions(mapx, mapy);
CREATE INDEX IF NOT EXISTS idx_public_pensions_name ON public_pensions(name_normalized);
CREATE INDEX IF NOT EXISTS idx_public_pensions_source ON public_pensions(source, source_id);
CREATE INDEX IF NOT EXISTS idx_public_pensions_claimed ON public_pensions(is_claimed, claimed_by);
CREATE UNIQUE INDEX IF NOT EXISTS idx_public_pensions_unique ON public_pensions(source, source_id);


-- 펜션-축제 매칭 테이블
CREATE TABLE IF NOT EXISTS pension_festival_matches (
  id INTEGER PRIMARY KEY AUTOINCREMENT,

  pension_id INTEGER NOT NULL,
  pension_type TEXT DEFAULT 'public',
  festival_id INTEGER NOT NULL,

  distance_km REAL,
  travel_time_min INTEGER,

  match_type TEXT,
  match_score INTEGER DEFAULT 0,

  is_featured INTEGER DEFAULT 0,

  created_at TEXT DEFAULT CURRENT_TIMESTAMP,

  FOREIGN KEY (festival_id) REFERENCES festivals(id),
  UNIQUE(pension_id, pension_type, festival_id)
);

-- 인덱스
CREATE INDEX IF NOT EXISTS idx_matches_pension ON pension_festival_matches(pension_id, pension_type);
CREATE INDEX IF NOT EXISTS idx_matches_festival ON pension_festival_matches(festival_id);
CREATE INDEX IF NOT EXISTS idx_matches_distance ON pension_festival_matches(distance_km);


-- 지역코드 테이블
CREATE TABLE IF NOT EXISTS area_codes (
  code TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  name_short TEXT,
  name_en TEXT
);

-- 시군구코드 테이블
CREATE TABLE IF NOT EXISTS sigungu_codes (
  area_code TEXT NOT NULL,
  sigungu_code TEXT NOT NULL,
  name TEXT NOT NULL,
  name_en TEXT,
  PRIMARY KEY (area_code, sigungu_code),
  FOREIGN KEY (area_code) REFERENCES area_codes(code)
);


-- 펜션 클레임 테이블
CREATE TABLE IF NOT EXISTS pension_claims (
  id INTEGER PRIMARY KEY AUTOINCREMENT,

  public_pension_id INTEGER NOT NULL,
  user_id INTEGER NOT NULL,

  status TEXT DEFAULT 'pending',
  verification_method TEXT,
  verification_data TEXT,

  reviewed_by INTEGER,
  reviewed_at TEXT,
  reject_reason TEXT,

  created_at TEXT DEFAULT CURRENT_TIMESTAMP,

  FOREIGN KEY (public_pension_id) REFERENCES public_pensions(id),
  FOREIGN KEY (user_id) REFERENCES users(id),
  FOREIGN KEY (reviewed_by) REFERENCES users(id)
);


-- 지역코드 초기 데이터
INSERT OR IGNORE INTO area_codes (code, name, name_short, name_en) VALUES
('1', '서울특별시', '서울', 'Seoul'),
('2', '인천광역시', '인천', 'Incheon'),
('3', '대전광역시', '대전', 'Daejeon'),
('4', '대구광역시', '대구', 'Daegu'),
('5', '광주광역시', '광주', 'Gwangju'),
('6', '부산광역시', '부산', 'Busan'),
('7', '울산광역시', '울산', 'Ulsan'),
('8', '세종특별자치시', '세종', 'Sejong'),
('31', '경기도', '경기', 'Gyeonggi'),
('32', '강원특별자치도', '강원', 'Gangwon'),
('33', '충청북도', '충북', 'Chungbuk'),
('34', '충청남도', '충남', 'Chungnam'),
('35', '경상북도', '경북', 'Gyeongbuk'),
('36', '경상남도', '경남', 'Gyeongnam'),
('37', '전북특별자치도', '전북', 'Jeonbuk'),
('38', '전라남도', '전남', 'Jeonnam'),
('39', '제주특별자치도', '제주', 'Jeju');


-- pension_profiles 테이블에 컬럼 추가 (이미 존재하면 무시)
-- SQLite는 IF NOT EXISTS를 ALTER TABLE에서 지원하지 않으므로 별도 처리 필요
-- 아래는 참고용, 실제로는 코드에서 처리

-- ALTER TABLE pension_profiles ADD COLUMN mapx REAL;
-- ALTER TABLE pension_profiles ADD COLUMN mapy REAL;
-- ALTER TABLE pension_profiles ADD COLUMN area_code TEXT;
-- ALTER TABLE pension_profiles ADD COLUMN sigungu_code TEXT;
-- ALTER TABLE pension_profiles ADD COLUMN public_pension_id INTEGER REFERENCES public_pensions(id);
