import { InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { type AiSettingsDto } from '../../queries/get-ai-settings/get-ai-settings.handler';
import { SystemSettingsService } from '../../services/system-settings.service';
import { UpdateAiSettingsCommand } from './update-ai-settings.command';

@CommandHandler(UpdateAiSettingsCommand)
export class UpdateAiSettingsHandler
  implements ICommandHandler<UpdateAiSettingsCommand>
{
  constructor(
    private readonly systemSettings: SystemSettingsService,
    private readonly logger: LoggerService,
  ) {}

  async execute(command: UpdateAiSettingsCommand): Promise<AiSettingsDto> {
    try {
      const updated = await this.systemSettings.updateAiSettings({
        apiUrl: command.apiUrl,
        apiKey: command.apiKey,
        model: command.model,
        updatedBy: command.adminId,
      });

      return {
        apiUrl: updated.apiUrl,
        apiKeyMasked: SystemSettingsService.maskApiKey(updated.apiKey),
        model: updated.model,
        hasApiKey: Boolean(updated.apiKey),
        updatedAt: updated.updatedAt ? updated.updatedAt.toISOString() : null,
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to update AI settings: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'UpdateAiSettingsHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lưu cài đặt AI');
    }
  }
}
