import { Inject, InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import {
  MARKET_INDEX_REPOSITORY,
  type IMarketIndexRepository,
  type MarketReportResult,
} from '../../../domain/repositories/market-index.repository';
import { GenerateReportCommand } from './generate-report.command';

export interface GenerateReportResult {
  city: string;
  period: string;
  data: MarketReportResult[];
  generatedAt: string;
}

@CommandHandler(GenerateReportCommand)
export class GenerateReportHandler implements ICommandHandler<GenerateReportCommand> {
  constructor(
    @Inject(MARKET_INDEX_REPOSITORY) private readonly marketIndexRepo: IMarketIndexRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(command: GenerateReportCommand): Promise<GenerateReportResult> {
    try {
      const data = await this.marketIndexRepo.getMarketReport(
        command.city,
        command.period,
        command.propertyType,
      );

      return {
        city: command.city,
        period: command.period,
        data,
        generatedAt: new Date().toISOString(),
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to tạo báo cáo thị trường: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể tạo báo cáo thị trường. Vui lòng thử lại sau.');
    }
  }
}
