/**
 * Authentication commands.
 */

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

export const authCommand = new Command('auth')
  .description('Authentication commands')
  .addCommand(
    new Command('login')
      .description('Login with GitHub')
      .action(async () => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          const loginData = await client.authLogin();
          console.log();
          console.log('GitHub Device Authorization');
          console.log('──────────────────────────────────────');
          console.log();
          console.log(`  Open: ${style.primary(loginData.verification_uri)}`);
          console.log(`  Code: ${style.bold(loginData.user_code)}`);
          console.log();
          console.log('Waiting for authorization...');

          // Poll for completion
          const pollInterval = (loginData.interval || 5) * 1000;
          const expiresAt = Date.now() + loginData.expires_in * 1000;

          while (Date.now() < expiresAt) {
            await new Promise((resolve) => setTimeout(resolve, pollInterval));

            const pollResult = await client.authPoll(loginData.user_code);

            if (pollResult.status === 'success') {
              console.log();
              console.log(style.success(`Logged in as ${pollResult.username}`));
              return;
            } else if (pollResult.status === 'expired') {
              console.log();
              console.error(style.error('Authorization expired'));
              process.exit(1);
            } else if (pollResult.status === 'error') {
              console.log();
              console.error(style.error(`Error: ${pollResult.error}`));
              process.exit(1);
            }
          }

          console.log();
          console.error(style.error('Authorization timed out'));
          process.exit(1);
        } catch (error) {
          console.error(style.error('Login failed:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('logout')
      .description('Sign out')
      .action(async () => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          await client.authLogout();
          console.log(style.success('Logged out successfully'));
        } catch (error) {
          console.error(style.error('Logout failed:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('status')
      .description('Show authentication status')
      .action(async () => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          const status = await client.authStatus();
          if (status.authenticated) {
            console.log(style.success(`Authenticated as ${status.username}`));
            if (status.scope) {
              console.log(`  Scope: ${status.scope}`);
            }
          } else {
            console.log(style.muted('Not authenticated'));
            console.log('  Run `emdash-ts auth login` to sign in');
          }
        } catch (error) {
          console.error(style.error('Failed to get status:'), (error as Error).message);
          process.exit(1);
        }
      })
  );
