import Database from 'better-sqlite3';
import { app } from 'electron';
import path from 'path';
import fs from 'fs';

export interface PriceAlert {
  id: string;
  auecAmount: number;
  maxPrice: number;
  enabled: boolean;
}

let db: Database.Database | null = null;

export function initDatabase() {
  const userDataPath = app.getPath('userData');
  const dbPath = path.join(userDataPath, 'alerts.db');
  
  // Ensure directory exists
  if (!fs.existsSync(userDataPath)) {
    fs.mkdirSync(userDataPath, { recursive: true });
  }
  
  db = new Database(dbPath);
  
  // Create alerts table
  db.exec(`
    CREATE TABLE IF NOT EXISTS alerts (
      id TEXT PRIMARY KEY,
      auecAmount REAL NOT NULL,
      maxPrice REAL NOT NULL,
      enabled INTEGER NOT NULL DEFAULT 1
    )
  `);
  
  // Create settings table for custom AUEC amount
  db.exec(`
    CREATE TABLE IF NOT EXISTS settings (
      key TEXT PRIMARY KEY,
      value TEXT NOT NULL
    )
  `);
  
  console.log('Database initialized at:', dbPath);
}

export function getAllAlerts(): PriceAlert[] {
  if (!db) throw new Error('Database not initialized');
  
  const stmt = db.prepare('SELECT * FROM alerts');
  const rows = stmt.all() as any[];
  
  return rows.map(row => ({
    id: row.id,
    auecAmount: row.auecAmount,
    maxPrice: row.maxPrice,
    enabled: row.enabled === 1,
  }));
}

export function addAlert(alert: PriceAlert): void {
  if (!db) throw new Error('Database not initialized');
  
  const stmt = db.prepare(`
    INSERT INTO alerts (id, auecAmount, maxPrice, enabled)
    VALUES (?, ?, ?, ?)
  `);
  
  stmt.run(alert.id, alert.auecAmount, alert.maxPrice, alert.enabled ? 1 : 0);
}

export function updateAlert(alert: PriceAlert): void {
  if (!db) throw new Error('Database not initialized');
  
  const stmt = db.prepare(`
    UPDATE alerts
    SET auecAmount = ?, maxPrice = ?, enabled = ?
    WHERE id = ?
  `);
  
  stmt.run(alert.auecAmount, alert.maxPrice, alert.enabled ? 1 : 0, alert.id);
}

export function deleteAlert(id: string): void {
  if (!db) throw new Error('Database not initialized');
  
  const stmt = db.prepare('DELETE FROM alerts WHERE id = ?');
  stmt.run(id);
}

export function getCustomAuecAmount(): number | null {
  if (!db) throw new Error('Database not initialized');
  
  const stmt = db.prepare('SELECT value FROM settings WHERE key = ?');
  const row = stmt.get('customAuecAmount') as any;
  
  return row ? parseFloat(row.value) : null;
}

export function setCustomAuecAmount(amount: number): void {
  if (!db) throw new Error('Database not initialized');
  
  const stmt = db.prepare(`
    INSERT OR REPLACE INTO settings (key, value)
    VALUES (?, ?)
  `);
  
  stmt.run('customAuecAmount', amount.toString());
}

export function closeDatabase(): void {
  if (db) {
    db.close();
    db = null;
  }
}
