import { drizzle } from 'drizzle-orm/better-sqlite3';
import Database from 'better-sqlite3';
import * as schema from '../db/schema.js';
import { env } from './env.js';
import fs from 'fs';
import path from 'path';

if (!env.DATABASE_PATH) {
  throw new Error('DATABASE_PATH environment variable is not set');
}

// Ensure directory exists BEFORE opening the database file
const dbDir = path.dirname(env.DATABASE_PATH);
if (!fs.existsSync(dbDir)) {
  fs.mkdirSync(dbDir, { recursive: true });
}

const sqlite = new Database(env.DATABASE_PATH);

// Enable WAL mode for better concurrent access
sqlite.pragma('journal_mode = WAL');

export const db = drizzle(sqlite, { schema });

// Auto-create tables if they don't exist
export function initDatabase() {
  console.log('🔧 Initializing database...');

  try {
    // Check if users table exists (acts as a sentinel for initial setup)
    const tableCheck = sqlite
      .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")
      .get();

    if (!tableCheck) {
      console.log('📝 Creating database schema...');

      sqlite.exec(`
        PRAGMA foreign_keys = ON;

        CREATE TABLE IF NOT EXISTS users (
          id TEXT PRIMARY KEY,
          gitea_id TEXT UNIQUE NOT NULL,
          gitea_username TEXT NOT NULL,
          gitea_email TEXT,
          display_name TEXT,
          avatar_url TEXT,
          role TEXT DEFAULT 'admin',
          created_at INTEGER DEFAULT (unixepoch()),
          last_login INTEGER
        );

        CREATE TABLE IF NOT EXISTS events (
          id TEXT PRIMARY KEY,
          title TEXT NOT NULL,
          date TEXT NOT NULL,
          description TEXT NOT NULL,
          image_url TEXT NOT NULL,
          display_order INTEGER NOT NULL,
          is_published INTEGER DEFAULT 1,
          created_at INTEGER DEFAULT (unixepoch()),
          updated_at INTEGER DEFAULT (unixepoch())
        );

        CREATE TABLE IF NOT EXISTS gallery_images (
          id TEXT PRIMARY KEY,
          image_url TEXT NOT NULL,
          alt_text TEXT NOT NULL,
          display_order INTEGER NOT NULL,
          is_published INTEGER DEFAULT 1,
          created_at INTEGER DEFAULT (unixepoch())
        );

        CREATE TABLE IF NOT EXISTS content_sections (
          id TEXT PRIMARY KEY,
          section_name TEXT UNIQUE NOT NULL,
          content_json TEXT NOT NULL,
          updated_at INTEGER DEFAULT (unixepoch())
        );

        CREATE TABLE IF NOT EXISTS site_settings (
          key TEXT PRIMARY KEY,
          value TEXT NOT NULL,
          updated_at INTEGER DEFAULT (unixepoch())
        );

        CREATE TABLE IF NOT EXISTS publish_history (
          id TEXT PRIMARY KEY,
          user_id TEXT REFERENCES users(id),
          commit_hash TEXT,
          commit_message TEXT,
          published_at INTEGER DEFAULT (unixepoch())
        );
      `);

      console.log('✅ Database schema created successfully!');
    } else {
      console.log('✅ Database already initialized.');
    }
  } catch (error) {
    console.error('❌ Error initializing database:', error);
    throw error;
  }
}
