// Quick database access script
// Usage: node scripts/db-access.js

import Database from 'better-sqlite3';
import path from 'path';
import readline from 'readline';
import fs from 'fs';
import { fileURLToPath } from 'url';

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

const dbPath = path.join(process.cwd(), 'data', 'users.db');
if (!fs.existsSync(dbPath)) {
  console.error('❌ Database not found at:', dbPath);
  process.exit(1);
}

const db = new Database(dbPath);

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log('📊 Database Access Tool');
console.log('Database path:', dbPath);
console.log('\nAvailable commands:');
console.log('  list - List all users');
console.log('  count - Count total users');
console.log('  schema - Show table schema');
console.log('  search <name> - Search user by name');
console.log('  user <username> - Get user by username');
console.log('  query <SQL> - Run custom SQL query');
console.log('  exit - Exit\n');

function prompt() {
  rl.question('> ', (input) => {
    const trimmed = input.trim();
    if (!trimmed) {
      prompt();
      return;
    }
    
    const [cmd, ...args] = trimmed.split(' ');
    
    try {
      switch(cmd.toLowerCase()) {
        case 'list':
          const users = db.prepare('SELECT id, namaLengkap, namaUser, email, tipeUser FROM users LIMIT 50').all();
          if (users.length === 0) {
            console.log('No users found.');
          } else {
            console.table(users);
            console.log(`\nShowing ${users.length} users`);
          }
          break;
          
        case 'count':
          const count = db.prepare('SELECT COUNT(*) as total FROM users').get();
          console.log(`\nTotal users: ${count.total}`);
          break;
          
        case 'schema':
          const schema = db.prepare("PRAGMA table_info(users)").all();
          console.table(schema);
          break;
          
        case 'search':
          const searchTerm = args.join(' ');
          if (!searchTerm) {
            console.log('Error: Please provide search term');
            break;
          }
          const searchResults = db.prepare(`
            SELECT id, namaLengkap, namaUser, email, tipeUser 
            FROM users 
            WHERE namaLengkap LIKE ? OR namaUser LIKE ?
          `).all(`%${searchTerm}%`, `%${searchTerm}%`);
          if (searchResults.length === 0) {
            console.log('No users found.');
          } else {
            console.table(searchResults);
          }
          break;
          
        case 'user':
          const username = args.join(' ');
          if (!username) {
            console.log('Error: Please provide username');
            break;
          }
          const user = db.prepare('SELECT * FROM users WHERE namaUser = ?').get(username);
          if (!user) {
            console.log('User not found.');
          } else {
            console.log('\nUser Details:');
            console.log(JSON.stringify(user, null, 2));
          }
          break;
          
        case 'query':
          const sql = args.join(' ');
          if (!sql) {
            console.log('Error: Please provide SQL query');
            break;
          }
          const result = db.prepare(sql).all();
          if (result.length === 0) {
            console.log('No results.');
          } else {
            console.table(result);
          }
          break;
          
        case 'exit':
        case 'quit':
        case 'q':
          db.close();
          rl.close();
          console.log('\n👋 Goodbye!');
          return;
          
        default:
          console.log('Unknown command. Type "exit" to quit.');
      }
    } catch (error) {
      console.error('❌ Error:', error.message);
    }
    
    console.log(''); // Empty line for readability
    prompt();
  });
}

// Handle Ctrl+C
rl.on('SIGINT', () => {
  console.log('\n\n👋 Goodbye!');
  db.close();
  rl.close();
  process.exit(0);
});

prompt();



