const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const fs = require('fs');
const bcrypt = require('bcrypt');

// Check for environment variable for database path
let dbPath;

if (process.env.DB_PATH) {
  // If DB_PATH environment variable is set, use it
  dbPath = process.env.DB_PATH;
  // Ensure the directory exists
  const dbDir = path.dirname(dbPath);
  if (!fs.existsSync(dbDir)) {
    fs.mkdirSync(dbDir, { recursive: true });
  }
} else {
  // Default: Create database directory if it doesn't exist
  const dbDir = path.join(__dirname, '..', '..', 'data');
  if (!fs.existsSync(dbDir)) {
    fs.mkdirSync(dbDir, { recursive: true });
  }
  // Create and initialize SQLite database with default path
  dbPath = path.join(dbDir, 'project_tracker.sqlite');
}
const db = new sqlite3.Database(dbPath);

// Helper to run queries as promises
const query = (sql, params = []) => {
  return new Promise((resolve, reject) => {
    db.all(sql, params, (err, rows) => {
      if (err) {
        console.error('SQLite error:', err);
        return reject(err);
      }
      resolve({ rows });
    });
  });
};

// Helper to run single row queries
const queryOne = (sql, params = []) => {
  return new Promise((resolve, reject) => {
    db.get(sql, params, (err, row) => {
      if (err) {
        console.error('SQLite error:', err);
        return reject(err);
      }
      resolve(row ? { rows: [row] } : { rows: [] });
    });
  });
};

// Helper to run insert, update, delete operations
const run = (sql, params = []) => {
  return new Promise((resolve, reject) => {
    db.run(sql, params, function(err) {
      if (err) {
        console.error('SQLite error:', err);
        return reject(err);
      }
      resolve({ rows: [{ id: this.lastID }] });
    });
  });
};

// Initialize database schema
const initDatabase = async () => {
  try {
    // Create users table
    await run(`
      CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL,
        email TEXT UNIQUE NOT NULL,
        password TEXT NOT NULL,
        role TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    `);

    // Create projects table
    await run(`
      CREATE TABLE IF NOT EXISTS projects (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        description TEXT,
        start_date TEXT,
        end_date TEXT,
        completion_percentage INTEGER DEFAULT 0,
        notes TEXT,
        created_by INTEGER NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (created_by) REFERENCES users (id)
      )
    `);

    // Create project_shares table
    await run(`
      CREATE TABLE IF NOT EXISTS project_shares (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        project_id INTEGER NOT NULL,
        share_id TEXT UNIQUE NOT NULL,
        password TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (project_id) REFERENCES projects (id)
      )
    `);

    // Create project_permissions table
    await run(`
      CREATE TABLE IF NOT EXISTS project_permissions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        project_id INTEGER NOT NULL,
        user_id INTEGER NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (project_id) REFERENCES projects (id),
        FOREIGN KEY (user_id) REFERENCES users (id)
      )
    `);

    // Count existing super_admin users
    const adminCount = await queryOne(
      'SELECT COUNT(*) as count FROM users WHERE role = ?',
      ['super_admin']
    );

    // Create default admin user ONLY if no super_admin exists at all
    if (adminCount.rows.length === 0 || adminCount.rows[0].count === 0) {
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash('password123', salt);
      
      await run(
        'INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)',
        ['Admin', 'admin@projecttracker.com', hashedPassword, 'super_admin']
      );
      
      console.log('Default admin user created - only one super_admin will ever be created');
    } else {
      console.log('Super admin already exists - skipping admin creation');
    }

    console.log('Database initialized successfully');
  } catch (error) {
    console.error('Database initialization error:', error);
  }
};

// Database initialization flag to ensure it only runs once
let dbInitialized = false;

// Initialize database
if (!dbInitialized) {
  initDatabase();
  dbInitialized = true;
}

// Export query functions
module.exports = {
  query,
  queryOne,
  run,
};
