/**
 * Database commands.
 */

import { Command } from 'commander';
import { EmdashClient } from '../client.js';
import { getServerManager } from '../server-manager.js';
import { style } from '../design.js';

export const dbCommand = new Command('db')
  .description('Database management commands')
  .addCommand(
    new Command('init')
      .description('Initialize the database schema')
      .action(async () => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          await client.dbInit();
          console.log(style.success('Database initialized successfully'));
        } catch (error) {
          console.error(style.error('Failed to initialize database:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('clear')
      .description('Clear all data from the database')
      .option('-y, --yes', 'Skip confirmation')
      .action(async (options: { yes?: boolean }) => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        if (!options.yes) {
          const readline = await import('node:readline');
          const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout,
          });

          const answer = await new Promise<string>((resolve) => {
            rl.question('Are you sure you want to clear all data? (y/N): ', resolve);
          });
          rl.close();

          if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {
            console.log('Cancelled');
            return;
          }
        }

        try {
          await client.dbClear(true);
          console.log(style.success('Database cleared successfully'));
        } catch (error) {
          console.error(style.error('Failed to clear database:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('stats')
      .description('Show database statistics')
      .action(async () => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          const stats = await client.dbStats();
          console.log('Database Statistics:');
          console.log(`  Nodes: ${stats.nodes}`);
          console.log(`  Edges: ${stats.edges}`);
          console.log(`  Functions: ${stats.functions}`);
          console.log(`  Classes: ${stats.classes}`);
          console.log(`  Files: ${stats.files}`);
        } catch (error) {
          console.error(style.error('Failed to get stats:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('test')
      .description('Test database connection')
      .action(async () => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          await client.dbTest();
          console.log(style.success('Database connection successful'));
        } catch (error) {
          console.error(style.error('Database connection failed:'), (error as Error).message);
          process.exit(1);
        }
      })
  );
