import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import {
  CreateFormatoAcreditacionDto,
  QueryFormatosDto,
  UpdateFormatoAcreditacionDto,
} from '../dto/acreditaciones-bancarias.dto';

@Injectable()
export class FormatosBancariosService {
  constructor(private readonly prisma: PrismaService) {}

  listar(empresaId: string, query: QueryFormatosDto) {
    const where: Prisma.rrhh_formatos_acreditacion_bancariaWhereInput = { empresa_id: empresaId };
    if (query.banco_id) where.banco_id = query.banco_id;
    return this.prisma.rrhh_formatos_acreditacion_bancaria.findMany({
      where,
      orderBy: [{ banco: { descripcion: 'asc' } }, { nombre: 'asc' }],
      include: { banco: { select: { id: true, codigo: true, descripcion: true } } },
    });
  }

  async obtener(id: string, empresaId: string) {
    const f = await this.prisma.rrhh_formatos_acreditacion_bancaria.findFirst({
      where: { id, empresa_id: empresaId },
      include: { banco: { select: { id: true, codigo: true, descripcion: true } } },
    });
    if (!f) throw new NotFoundException('Formato no encontrado');
    return f;
  }

  async crear(empresaId: string, dto: CreateFormatoAcreditacionDto) {
    const banco = await this.prisma.bancos.findFirst({
      where: { id: dto.banco_id, OR: [{ empresa_id: empresaId }, { empresa_id: null }] },
    });
    if (!banco) throw new BadRequestException('Banco inválido para esta empresa');
    if (!dto.template_detalle?.trim()) throw new BadRequestException('template_detalle es obligatorio');

    return this.prisma.rrhh_formatos_acreditacion_bancaria.create({
      data: {
        empresa_id: empresaId,
        banco_id: dto.banco_id,
        nombre: dto.nombre,
        encoding: dto.encoding ?? 'UTF-8',
        separador_lineas: dto.separador_lineas ?? '\\n',
        separador_campos: dto.separador_campos,
        tipo_archivo: dto.tipo_archivo ?? 'DELIMITADO',
        tiene_cabecera: dto.tiene_cabecera ?? false,
        tiene_pie: dto.tiene_pie ?? false,
        template_cabecera: dto.template_cabecera,
        template_detalle: dto.template_detalle,
        template_pie: dto.template_pie,
        extension_archivo: dto.extension_archivo ?? 'txt',
        descripcion: dto.descripcion,
        activo: dto.activo ?? true,
      },
    });
  }

  async actualizar(id: string, empresaId: string, dto: UpdateFormatoAcreditacionDto) {
    const f = await this.prisma.rrhh_formatos_acreditacion_bancaria.findFirst({
      where: { id, empresa_id: empresaId },
    });
    if (!f) throw new NotFoundException('Formato no encontrado');
    return this.prisma.rrhh_formatos_acreditacion_bancaria.update({
      where: { id },
      data: { ...dto, updated_at: new Date() },
    });
  }

  async eliminar(id: string, empresaId: string) {
    const f = await this.prisma.rrhh_formatos_acreditacion_bancaria.findFirst({
      where: { id, empresa_id: empresaId },
    });
    if (!f) throw new NotFoundException('Formato no encontrado');
    const enUso = await this.prisma.rrhh_acreditaciones_bancarias.count({ where: { formato_id: id } });
    if (enUso > 0) {
      throw new BadRequestException(
        'Este formato ya fue usado para generar acreditaciones. Desactivalo en lugar de eliminarlo.',
      );
    }
    return this.prisma.rrhh_formatos_acreditacion_bancaria.delete({ where: { id } });
  }
}
