// Database initialization - loaded at runtime after entrypoint runs
import path from 'path'
import { existsSync, mkdirSync, chmodSync } from 'fs'
import sqlite3 from 'better-sqlite3'

const dbPath = path.join(new URL(import.meta.url).pathname, '..', 'db', 'queuenorth.db')
const dbDir = path.dirname(dbPath)

// Ensure db directory exists with proper permissions
if (!existsSync(dbDir)) {
  mkdirSync(dbDir, { recursive: true })
  try { chmodSync(dbDir, 0o777) } catch (e) {}
}

// Ensure db file has proper permissions if it exists
if (existsSync(dbPath)) {
  try { chmodSync(dbPath, 0o666) } catch (e) {}
}

// Initialize the database
export const db = sqlite3(dbPath)

// Initialize schema
export const initSchema = () => {
  // Leads table
  db.exec(`
    CREATE TABLE IF NOT EXISTS leads (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      company TEXT NOT NULL,
      name TEXT NOT NULL,
      email TEXT NOT NULL,
      phone TEXT,
      zip TEXT,
      message TEXT,
      service_interest TEXT,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  `)

  // Support requests table
  db.exec(`
    CREATE TABLE IF NOT EXISTS support_requests (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      company TEXT NOT NULL,
      email TEXT NOT NULL,
      phone TEXT,
      issue TEXT NOT NULL,
      priority TEXT DEFAULT 'medium',
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  `)
}

initSchema()
