import Database from 'better-sqlite3';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

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

const dbPath = process.env.DATABASE_PATH || join(__dirname, '..', 'orders.db');

// Initialize database
export const db = new Database(dbPath);

// Enable foreign keys
db.pragma('foreign_keys = ON');

// Create orders table
const createOrdersTable = () => {
  const sql = `
    CREATE TABLE IF NOT EXISTS orders (
      id TEXT PRIMARY KEY,
      stripe_session_id TEXT UNIQUE NOT NULL,
      stripe_payment_intent TEXT,
      wren_order_id TEXT,
      customer_email TEXT,
      tons REAL NOT NULL,
      portfolio_id INTEGER NOT NULL,
      base_amount INTEGER NOT NULL,
      processing_fee INTEGER NOT NULL,
      total_amount INTEGER NOT NULL,
      currency TEXT DEFAULT 'USD',
      status TEXT DEFAULT 'pending',
      created_at TEXT DEFAULT CURRENT_TIMESTAMP,
      updated_at TEXT DEFAULT CURRENT_TIMESTAMP
    )
  `;

  // Using better-sqlite3's prepare/run for safety (not child_process)
  db.prepare(sql).run();
  console.log('✅ Orders table created successfully');
};

// Create indexes for faster lookups
const createIndexes = () => {
  const indexes = [
    'CREATE INDEX IF NOT EXISTS idx_stripe_session_id ON orders(stripe_session_id)',
    'CREATE INDEX IF NOT EXISTS idx_status ON orders(status)',
    'CREATE INDEX IF NOT EXISTS idx_created_at ON orders(created_at)'
  ];

  indexes.forEach(indexSql => db.prepare(indexSql).run());
  console.log('✅ Database indexes created successfully');
};

// Initialize database schema
export const initializeDatabase = () => {
  try {
    createOrdersTable();
    createIndexes();
    console.log('✅ Database initialized successfully');
    return true;
  } catch (error) {
    console.error('❌ Database initialization failed:', error);
    return false;
  }
};

// Run initialization if called directly
if (import.meta.url === `file://${process.argv[1]}`) {
  initializeDatabase();
  db.close();
}

export default db;
