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

/**
 * Use case for clearing the user's session (logout).
 * 
 * Removes stored browser context and cookies, effectively logging
 * the user out. The next automation attempt will require re-authentication.
 */
export class ClearSessionUseCase {
  constructor(
    private readonly authService: AuthenticationServicePort,
    private readonly logger: Logger, // Inject Logger
  ) {}

  /**
   * Execute the session clearing.
   * 
   * @returns Result indicating success or failure
   */
  async execute(): Promise<Result<void>> {
    this.logger.debug('Attempting to clear user session.', {
      useCase: 'ClearSessionUseCase'
    });
    try {
      const result = await this.authService.clearSession();

      if (result.isOk()) {
        this.logger.info('User session cleared successfully.', {
          useCase: 'ClearSessionUseCase'
        });
      } else {
        this.logger.warn('Failed to clear user session.', {
          useCase: 'ClearSessionUseCase',
          error: result.error,
        });
      }
      return result;
    } catch (error) {
      const err = error instanceof Error ? error : new Error(String(error));
      this.logger.error('Error clearing user session.', err, {
        useCase: 'ClearSessionUseCase'
      });
      return Result.err(err);
    }
  }
}
