import { InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { SystemSettingsService } from '../../services/system-settings.service';
import { GetAiSettingsQuery } from './get-ai-settings.query';

export interface AiSettingsDto {
  apiUrl: string;
  apiKeyMasked: string | null;
  model: string;
  hasApiKey: boolean;
  updatedAt: string | null;
}

@QueryHandler(GetAiSettingsQuery)
export class GetAiSettingsHandler implements IQueryHandler<GetAiSettingsQuery> {
  constructor(
    private readonly systemSettings: SystemSettingsService,
    private readonly logger: LoggerService,
  ) {}

  async execute(_query: GetAiSettingsQuery): Promise<AiSettingsDto> {
    try {
      const current = await this.systemSettings.getAiSettings();
      return {
        apiUrl: current.apiUrl,
        apiKeyMasked: SystemSettingsService.maskApiKey(current.apiKey),
        model: current.model,
        hasApiKey: Boolean(current.apiKey),
        updatedAt: current.updatedAt ? current.updatedAt.toISOString() : null,
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get AI settings: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetAiSettingsHandler',
      );
      throw new InternalServerErrorException('Lỗi khi đọc cài đặt AI');
    }
  }
}
