import Database from 'better-sqlite3'
import path from 'path'
import fs from 'fs'

let _db: Database.Database | null = null

export function getDb(): Database.Database {
  if (_db) return _db

  const dbPath = process.env.DB_PATH || path.join(process.cwd(), 'data', 'casino.db')
  const dir = path.dirname(dbPath)
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })

  _db = new Database(dbPath)
  _db.pragma('journal_mode = WAL')
  _db.pragma('foreign_keys = ON')
  return _db
}

export interface Casino {
  id: number
  slug: string
  brand: string
  rating: number
  founded: number | null
  license: string | null
  min_deposit: number | null
  bonus_amount: string | null
  bonus_wagering: string | null
  payout_speed: string | null
  payment_methods: string   // JSON
  categories: string        // JSON
  pay_n_play: number
  featured: number
  featured_order: number
  affiliate_url: string | null
  content_sv: string | null
  meta_title: string | null
  meta_desc: string | null
  active: number
  last_updated: string
}

export interface Article {
  id: number
  slug: string
  title: string
  content_sv: string | null
  category: string | null
  featured: number
  published: number
  published_at: string | null
  meta_title: string | null
  meta_desc: string | null
  last_updated: string
}

export interface Category {
  id: number
  slug: string
  name_sv: string
  description_sv: string | null
  meta_title: string | null
  meta_desc: string | null
  active: number
}

export function parseMethods(json: string): string[] {
  try { return JSON.parse(json) } catch { return [] }
}

export function parseCategories(json: string): string[] {
  try { return JSON.parse(json) } catch { return [] }
}
