import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateZonaCobranzaDto, UpdateZonaCobranzaDto } from './dto';

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

  async create(empresaId: string, dto: CreateZonaCobranzaDto) {
    return this.prisma.zonas_cobranza.create({
      data: {
        empresa_id: empresaId,
        nombre: dto.nombre,
        descripcion: dto.descripcion,
        active: dto.active ?? true,
      },
    });
  }

  async findAll(empresaId: string, activeOnly = false) {
    return this.prisma.zonas_cobranza.findMany({
      where: {
        empresa_id: empresaId,
        ...(activeOnly && { active: true }),
      },
      include: {
        _count: {
          select: { vendedores_cobradores: true },
        },
      },
      orderBy: { nombre: 'asc' },
    });
  }

  async findOne(empresaId: string, id: string) {
    const zona = await this.prisma.zonas_cobranza.findFirst({
      where: { id, empresa_id: empresaId },
      include: {
        vendedores_cobradores: {
          where: { active: true },
          select: {
            id: true,
            nombre: true,
            apellido: true,
            tipo: true,
          },
        },
      },
    });

    if (!zona) {
      throw new NotFoundException('Zona de cobranza no encontrada');
    }

    return zona;
  }

  async update(empresaId: string, id: string, dto: UpdateZonaCobranzaDto) {
    await this.findOne(empresaId, id);

    return this.prisma.zonas_cobranza.update({
      where: { id },
      data: {
        nombre: dto.nombre,
        descripcion: dto.descripcion,
        active: dto.active,
        updated_at: new Date(),
      },
    });
  }

  async remove(empresaId: string, id: string) {
    await this.findOne(empresaId, id);

    return this.prisma.zonas_cobranza.update({
      where: { id },
      data: { active: false, updated_at: new Date() },
    });
  }

  async toggleActive(empresaId: string, id: string) {
    const zona = await this.findOne(empresaId, id);

    return this.prisma.zonas_cobranza.update({
      where: { id },
      data: { active: !zona.active, updated_at: new Date() },
    });
  }
}
