import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { IaProvider } from '../entities/ia-provider.entity'; import { UpdateProviderDto } from '../dto/provider.dto'; import { AuditLogService } from './audit-log.service'; @Injectable() export class AdminProvidersService { constructor( @InjectRepository(IaProvider) private providerRepository: Repository, private auditLogService: AuditLogService, ) {} async findAll(): Promise { return this.providerRepository.find({ order: { name: 'ASC' }, }); } async findOne(id: string): Promise { const provider = await this.providerRepository.findOne({ where: { id } }); if (!provider) { throw new NotFoundException('Proveedor IA no encontrado'); } return provider; } async findDefault(): Promise { return this.providerRepository.findOne({ where: { isDefault: true, isActive: true }, }); } async update( id: string, dto: UpdateProviderDto, userId: string, ): Promise { const provider = await this.findOne(id); const previousValue = { ...provider }; // If setting as default, unset other defaults if (dto.isDefault === true) { await this.providerRepository.update( { isDefault: true }, { isDefault: false }, ); } // Cannot unset the only default if (dto.isDefault === false && provider.isDefault) { const otherDefaults = await this.providerRepository.count({ where: { isDefault: true }, }); if (otherDefaults <= 1) { throw new BadRequestException('Debe haber al menos un proveedor por defecto'); } } Object.assign(provider, dto); const updated = await this.providerRepository.save(provider); await this.auditLogService.log({ userId, action: 'UPDATE_PROVIDER', resource: 'ia_providers', resourceId: id, previousValue, newValue: { ...updated }, }); return updated; } async getProviderByCode(code: string): Promise { return this.providerRepository.findOne({ where: { code, isActive: true }, }); } }