import { BadRequestException, Injectable } from '@nestjs/common';
import { AuditService } from 'src/audit/audit.service';
import { PrismaService } from 'src/prisma/prisma.service';
import { UpdateParametrosDto } from './dto/update-parametros.dto';

/**
 * Parámetros del vertical (M110). Una fila por empresa con los valores por defecto
 * decididos el 09–10/10/2026: base gravada 30 %, IVA 5 %, ajuste por IPC del BCP.
 * La fila nace sola la primera vez que se lee: sin paso manual post-deploy.
 */
@Injectable()
export class ParametrosInmService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
  ) {}

  async obtener(empresa_id: string) {
    const existente = await this.prisma.inm_parametros.findUnique({ where: { empresa_id } });
    if (existente) return existente;
    await this.prisma.inm_parametros.createMany({ data: [{ empresa_id }], skipDuplicates: true });
    return this.prisma.inm_parametros.findUniqueOrThrow({ where: { empresa_id } });
  }

  async actualizar(dto: UpdateParametrosDto, empresa_id: string, user_id?: string) {
    const anterior = await this.obtener(empresa_id);
    if (dto.producto_cuota_id) {
      const p = await this.prisma.productos.findFirst({
        where: { id: dto.producto_cuota_id, empresa_id },
        select: { id: true },
      });
      if (!p) throw new BadRequestException('El producto no existe en esta empresa');
    }
    if (dto.numeracion_id) {
      const n = await this.prisma.numeraciones_documento.findFirst({
        where: { id: dto.numeracion_id, empresa_id },
        select: { id: true },
      });
      if (!n) throw new BadRequestException('La numeración no existe en esta empresa');
    }
    if (dto.plantilla_boleto !== undefined) dto.plantilla_boleto = dto.plantilla_boleto?.trim() || null;
    const actualizado = await this.prisma.inm_parametros.update({
      where: { empresa_id },
      data: { ...dto, updated_at: new Date() },
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'inm_parametros',
      entity_id: actualizado.id,
      old_value: anterior,
      new_value: actualizado,
    });
    return actualizado;
  }
}
