import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService, NotFoundException, CacheService, CachePrefix, CacheTTL } from '@modules/shared';
import { USER_REPOSITORY, type IUserRepository } from '../../../domain/repositories/user.repository';
import { GetProfileQuery } from './get-profile.query';

export interface UserProfileDto {
  id: string;
  email: string | null;
  phone: string;
  fullName: string;
  avatarUrl: string | null;
  role: string;
  kycStatus: string;
  isActive: boolean;
  createdAt: Date;
}

@QueryHandler(GetProfileQuery)
export class GetProfileHandler implements IQueryHandler<GetProfileQuery> {
  constructor(
    @Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
    private readonly cache: CacheService,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetProfileQuery): Promise<UserProfileDto> {
    try {
      const cacheKey = CacheService.buildKey(CachePrefix.USER_PROFILE, query.userId);

      return this.cache.getOrSet(
        cacheKey,
        async () => {
          const user = await this.userRepo.findById(query.userId);
          if (!user) {
            throw new NotFoundException('Người dùng', query.userId);
          }

          return {
            id: user.id,
            email: user.email?.value ?? null,
            phone: user.phone.value,
            fullName: user.fullName,
            avatarUrl: user.avatarUrl,
            role: user.role,
            kycStatus: user.kycStatus,
            isActive: user.isActive,
            createdAt: user.createdAt,
          };
        },
        CacheTTL.USER_PROFILE,
        'user_profile',
      );
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get user profile: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể lấy thông tin hồ sơ người dùng');
    }
  }
}
