import Database from 'better-sqlite3';
import path from 'path';
import { fileURLToPath } from 'url';
import 'dotenv/config';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const DB_PATH = process.env.DB_PATH || path.join(__dirname, '../../data/meal-tracker.db');

let db;

export function getDb() {
  if (!db) {
    db = new Database(DB_PATH);
    db.pragma('journal_mode = WAL');
  }
  return db;
}

export function initialize() {
  const database = getDb();
  
  database.exec(`
    CREATE TABLE IF NOT EXISTS entries (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      description TEXT,
      image_url TEXT,
      notes TEXT,
      calories REAL DEFAULT 0,
      protein REAL DEFAULT 0,
      carbs REAL DEFAULT 0,
      fat REAL DEFAULT 0,
      created_at TEXT DEFAULT (datetime('now'))
    )
  `);

  database.exec(`
    CREATE INDEX IF NOT EXISTS idx_entries_created_at ON entries(created_at)
  `);

  console.log('Database initialized');
  return Promise.resolve();
}

export function getAll(dateFilter = null) {
  const db = getDb();
  let query = 'SELECT * FROM entries';
  let params = [];

  if (dateFilter) {
    query += ' WHERE date(created_at) = date(?)';
    params.push(dateFilter);
  }

  query += ' ORDER BY created_at DESC';
  
  const stmt = db.prepare(query);
  return params.length ? stmt.all(...params) : stmt.all();
}

export function getById(id) {
  const db = getDb();
  const stmt = db.prepare('SELECT * FROM entries WHERE id = ?');
  return stmt.get(id);
}

export function create(entry) {
  const db = getDb();
  const stmt = db.prepare(`
    INSERT INTO entries (name, description, image_url, notes, calories, protein, carbs, fat)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  `);
  
  const result = stmt.run(
    entry.name,
    entry.description || null,
    entry.image_url || null,
    entry.notes || null,
    entry.calories || 0,
    entry.protein || 0,
    entry.carbs || 0,
    entry.fat || 0
  );

  return { id: result.lastInsertRowid, ...entry };
}

export function remove(id) {
  const db = getDb();
  const stmt = db.prepare('DELETE FROM entries WHERE id = ?');
  const result = stmt.run(id);
  return result.changes > 0;
}

export function getDailyTotals(date) {
  const db = getDb();
  const stmt = db.prepare(`
    SELECT 
      SUM(calories) as total_calories,
      SUM(protein) as total_protein,
      SUM(carbs) as total_carbs,
      SUM(fat) as total_fat,
      COUNT(*) as entry_count
    FROM entries
    WHERE date(created_at) = date(?)
  `);
  
  const result = stmt.get(date);
  return {
    date,
    total_calories: result.total_calories || 0,
    total_protein: result.total_protein || 0,
    total_carbs: result.total_carbs || 0,
    total_fat: result.total_fat || 0,
    entry_count: result.entry_count || 0
  };
}
