import { Result } from '@core/shared/domain/Result';
import type { AuthenticationServicePort } from '../ports/AuthenticationServicePort';
import type { Logger } from '@core/shared/application/Logger';

/**
 * Use case for initiating the manual login flow.
 * 
 * Opens a visible browser window where the user can log into iRacing directly.
 * GridPilot never sees the credentials - it only waits for the URL to change
 * indicating successful login.
 */
export class InitiateLoginUseCase {
  constructor(
    private readonly authService: AuthenticationServicePort,
    private readonly logger: Logger,
  ) {}

  /**
   * Execute the login flow.
   * Opens browser and waits for user to complete manual login.
   * 
   * @returns Result indicating success (login complete) or failure (cancelled/timeout)
   */
  async execute(): Promise<Result<void>> {
    this.logger.debug('Initiating login flow...');
    try {
      const result = await this.authService.initiateLogin();
      if (result.isOk()) {
        this.logger.info('Login flow initiated successfully.');
      } else {
        this.logger.warn('Login flow initiation failed.', { error: result.error });
      }
      return result;
    } catch (error) {
      const err = error instanceof Error ? error : new Error(String(error));
      this.logger.error('Error initiating login flow.', err);
      return Result.err(err);
    }
  }
}