import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService, ValidationException } from '@modules/shared';
import { USER_REPOSITORY, type IUserRepository } from '../../../domain/repositories/user.repository';
import { GetMfaStatusQuery } from './get-mfa-status.query';

export interface MfaStatusDto {
  enabled: boolean;
  enabledAt: string | null;
  backupCodesRemaining: number;
}

@QueryHandler(GetMfaStatusQuery)
export class GetMfaStatusHandler implements IQueryHandler<GetMfaStatusQuery> {
  constructor(
    @Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetMfaStatusQuery): Promise<MfaStatusDto> {
    try {
      const user = await this.userRepo.findById(query.userId);
      if (!user) {
        throw new ValidationException('Người dùng không tồn tại');
      }

      return {
        enabled: user.totpEnabled,
        enabledAt: user.totpEnabledAt?.toISOString() ?? null,
        backupCodesRemaining: user.totpBackupCodes.length,
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get MFA status: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể lấy trạng thái MFA');
    }
  }
}
