#!/usr/bin/env node

const Database = require("better-sqlite3")
const path = require("path")
const fs = require("fs")

const DB_PATH = path.join(process.cwd(), "data", "quotes.db")
const dataDir = path.dirname(DB_PATH)

console.log("FoamKing Prisberegner - Database Setup")
console.log("======================================\n")

// Create data directory
if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir, { recursive: true })
  console.log("Created data/ directory")
}

// Check if DB already exists
const dbExists = fs.existsSync(DB_PATH)
if (dbExists) {
  console.log("Database already exists at", DB_PATH)
  console.log("Delete data/quotes.db to start fresh.\n")
  process.exit(0)
}

const db = new Database(DB_PATH)

db.pragma("journal_mode = WAL")

db.exec(`
  CREATE TABLE quotes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    postal_code TEXT NOT NULL,
    address TEXT,
    area REAL NOT NULL,
    height REAL NOT NULL,
    include_floor_heating INTEGER DEFAULT 1,
    flooring_type TEXT DEFAULT 'STANDARD',
    customer_name TEXT NOT NULL,
    customer_email TEXT NOT NULL,
    customer_phone TEXT NOT NULL,
    remarks TEXT,
    total_excl_vat REAL NOT NULL,
    total_incl_vat REAL NOT NULL,
    status TEXT DEFAULT 'new',
    created_at TEXT DEFAULT CURRENT_TIMESTAMP,
    email_opened_at TEXT
  )
`)

// Set auto-increment to start at 1000
db.exec(
  "INSERT INTO quotes (id, postal_code, area, height, customer_name, customer_email, customer_phone, total_excl_vat, total_incl_vat) VALUES (999, '0000', 0, 0, 'init', 'init', 'init', 0, 0)"
)
db.exec("DELETE FROM quotes WHERE id = 999")

db.close()

console.log("Database created at", DB_PATH)
console.log("Quote IDs will start at 1000.\n")
console.log("Next steps:")
console.log("  1. Configure .env.local (see SETUP.md / OPSÆTNING.md)")
console.log("  2. npm run build")
console.log("  3. npm start")
