import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { type LoggerService, UnauthorizedException } from '@modules/shared';
import { type TokenService, type TokenPair } from '../../../infrastructure/services/token.service';
import { LoginUserCommand } from './login-user.command';

@CommandHandler(LoginUserCommand)
export class LoginUserHandler implements ICommandHandler<LoginUserCommand> {
  constructor(
    private readonly tokenService: TokenService,
    private readonly logger: LoggerService,
  ) {}

  async execute(command: LoginUserCommand): Promise<TokenPair> {
    try {
      return await this.tokenService.generateTokenPair({
        sub: command.userId,
        phone: command.phone,
        role: command.role,
      });
    } catch (error) {
      this.logger.error(
        `Token generation failed for user ${command.userId}: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        'LoginUserHandler',
      );
      throw new UnauthorizedException('Không thể tạo phiên đăng nhập, vui lòng thử lại');
    }
  }
}
