import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';

const DB_DIR = path.join(process.env.HOME || '~', '.clawdbot/workspace/reonomy-api/data');
const DB_PATH = path.join(DB_DIR, 'reonomy.db');

let db: Database.Database;

export function getDb(): Database.Database {
  if (!db) {
    fs.mkdirSync(DB_DIR, { recursive: true });
    db = new Database(DB_PATH);
    db.pragma('journal_mode = WAL');
    db.pragma('foreign_keys = ON');
    initSchema();
  }
  return db;
}

function initSchema(): void {
  const d = getDb();

  d.exec(`
    CREATE TABLE IF NOT EXISTS jobs (
      id TEXT PRIMARY KEY,
      status TEXT NOT NULL DEFAULT 'pending',
      search_config TEXT NOT NULL,
      output_config TEXT NOT NULL,
      search_id TEXT,
      max_properties INTEGER NOT NULL DEFAULT 20,
      created_at TEXT NOT NULL,
      started_at TEXT,
      completed_at TEXT,
      error TEXT,
      progress_total INTEGER DEFAULT 0,
      progress_processed INTEGER DEFAULT 0,
      progress_leads INTEGER DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS leads (
      id TEXT PRIMARY KEY,
      job_id TEXT NOT NULL,
      scrape_date TEXT NOT NULL,
      property_id TEXT,
      property_address TEXT NOT NULL,
      building_data TEXT,
      sales_data TEXT,
      debt_data TEXT,
      tax_data TEXT,
      FOREIGN KEY (job_id) REFERENCES jobs(id)
    );

    CREATE TABLE IF NOT EXISTS owners (
      id TEXT PRIMARY KEY,
      lead_id TEXT NOT NULL,
      name TEXT NOT NULL,
      FOREIGN KEY (lead_id) REFERENCES leads(id)
    );

    CREATE TABLE IF NOT EXISTS contacts (
      id TEXT PRIMARY KEY,
      owner_id TEXT NOT NULL,
      type TEXT NOT NULL,
      value TEXT NOT NULL,
      label TEXT,
      FOREIGN KEY (owner_id) REFERENCES owners(id)
    );

    CREATE INDEX IF NOT EXISTS idx_leads_job ON leads(job_id);
    CREATE INDEX IF NOT EXISTS idx_owners_lead ON owners(lead_id);
    CREATE INDEX IF NOT EXISTS idx_contacts_owner ON contacts(owner_id);
  `);
}

export function closeDb(): void {
  if (db) {
    db.close();
  }
}
