import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { gym_modalidad_pago, gym_staff_tipo, gym_turno_estado } from '@prisma/client';
import { AuditService } from 'src/audit/audit.service';
import { PrismaService } from 'src/prisma/prisma.service';
import { monedaBaseOpcional } from 'src/utils/montos-moneda';
import { exigirIds, idsUnicos, lanzarSiHayErrores, textoONull } from '../common/gym-utils';
import { erroresStaff } from '../common/reglas';
import { CreateStaffGymDto, UpdateStaffGymDto } from './dto/staff.dto';
import { exigirSinHorariosActivos } from '../common/uso-horarios';

const INCLUDE = {
  empleado: { select: { id: true, nombres: true, apellidos: true, cedula_identidad: true } },
};

/**
 * Instructores (clases) y profesionales (masajistas y similares). El sueldo se
 * liquida por RRHH: acá sólo se vincula el empleado. Nunca se devuelve el pin_hash.
 */
@Injectable()
export class StaffGymService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
  ) {}

  private sinPin<T extends { pin_hash?: string | null }>(s: T) {
    const { pin_hash, ...resto } = s;
    return { ...resto, tiene_pin: !!pin_hash };
  }

  /** Cada persona trae la moneda base de la empresa para rotular su tarifa (por clase u hora). */
  async listar(empresa_id: string, filtros: { tipo?: gym_staff_tipo; incluir_inactivos?: boolean } = {}) {
    const [filas, moneda] = await Promise.all([
      this.prisma.gym_staff.findMany({
        where: {
          empresa_id,
          ...(filtros.incluir_inactivos ? {} : { activo: true }),
          ...(filtros.tipo && { tipo: filtros.tipo }),
        },
        include: INCLUDE,
        orderBy: [{ activo: 'desc' }, { nombre: 'asc' }],
      }),
      monedaBaseOpcional(this.prisma, empresa_id),
    ]);
    return filas.map((s) => ({ ...this.sinPin(s), moneda }));
  }

  /** Empleados activos de RRHH para vincular, por nombre o cédula. */
  empleados(empresa_id: string, q?: string) {
    const t = q?.trim();
    return this.prisma.rrhh_empleados.findMany({
      where: {
        empresa_id,
        estado: 'ACTIVO',
        ...(t && {
          OR: [
            { nombres: { contains: t, mode: 'insensitive' } },
            { apellidos: { contains: t, mode: 'insensitive' } },
            { cedula_identidad: { contains: t } },
          ],
        }),
      },
      select: { id: true, nombres: true, apellidos: true, cedula_identidad: true, telefono: true, email: true },
      orderBy: [{ apellidos: 'asc' }, { nombres: 'asc' }],
      take: 20,
    });
  }

  private async deEmpresa(id: string, empresa_id: string) {
    const s = await this.prisma.gym_staff.findFirst({ where: { id, empresa_id }, include: INCLUDE });
    if (!s) throw new NotFoundException('No se encontró la persona');
    return s;
  }

  private async validarReferencias(
    empresa_id: string,
    s: { empleado_id: string | null; actividad_ids: string[]; servicio_ids: string[]; sede_ids: string[] },
  ) {
    if (s.empleado_id) {
      const e = await this.prisma.rrhh_empleados.findFirst({ where: { id: s.empleado_id, empresa_id }, select: { id: true } });
      if (!e) throw new BadRequestException('El empleado no existe en esta empresa');
    }
    await exigirIds(
      s.actividad_ids,
      (ids) => this.prisma.gym_actividades.findMany({ where: { empresa_id, activo: true, id: { in: ids } }, select: { id: true } }),
      'Alguna de las actividades no existe o está dada de baja',
    );
    await exigirIds(
      s.servicio_ids,
      (ids) => this.prisma.gym_servicios.findMany({ where: { empresa_id, activo: true, id: { in: ids } }, select: { id: true } }),
      'Alguno de los servicios no existe o está dado de baja',
    );
    await exigirIds(
      s.sede_ids,
      (ids) => this.prisma.gym_sedes.findMany({ where: { empresa_id, activo: true, id: { in: ids } }, select: { id: true } }),
      'Alguna de las sedes no existe o está dada de baja',
    );
  }

  private async validarCi(empresa_id: string, ci: string | null, excepto?: string) {
    if (!ci) return;
    const otro = await this.prisma.gym_staff.findFirst({
      where: { empresa_id, ci, activo: true, ...(excepto && { id: { not: excepto } }) },
      select: { nombre: true },
    });
    if (otro) throw new ConflictException(`La cédula ${ci} ya está cargada (${otro.nombre})`);
  }

  async crear(dto: CreateStaffGymDto, empresa_id: string, user_id?: string) {
    const datos = {
      tipo: dto.tipo ?? gym_staff_tipo.INSTRUCTOR,
      nombre: dto.nombre.trim(),
      ci: textoONull(dto.ci),
      telefono: textoONull(dto.telefono),
      email: textoONull(dto.email),
      empleado_id: dto.empleado_id ?? null,
      actividad_ids: idsUnicos(dto.actividad_ids),
      servicio_ids: idsUnicos(dto.servicio_ids),
      sede_ids: idsUnicos(dto.sede_ids),
      modalidad_pago: dto.modalidad_pago ?? gym_modalidad_pago.FIJO,
      tarifa: dto.tarifa ?? null,
    };
    lanzarSiHayErrores(erroresStaff(datos));
    await this.validarReferencias(empresa_id, datos);
    await this.validarCi(empresa_id, datos.ci);
    const staff = await this.prisma.gym_staff.create({
      data: {
        empresa_id,
        ...datos,
        tarifa: datos.modalidad_pago === gym_modalidad_pago.FIJO ? null : datos.tarifa,
        created_by: user_id ?? null,
      },
      include: INCLUDE,
    });
    const limpio = this.sinPin(staff);
    await this.audit.log({ empresa_id, user_id, action: 'CREAR', entity_type: 'gym_staff', entity_id: staff.id, new_value: limpio });
    return limpio;
  }

  async actualizar(id: string, dto: UpdateStaffGymDto, empresa_id: string, user_id?: string) {
    const anterior = await this.deEmpresa(id, empresa_id);
    if (!anterior.activo) throw new ConflictException('Está dado de baja');
    const merged = {
      tipo: dto.tipo ?? anterior.tipo,
      nombre: dto.nombre?.trim() || anterior.nombre,
      ci: dto.ci !== undefined ? textoONull(dto.ci) : anterior.ci,
      telefono: dto.telefono !== undefined ? textoONull(dto.telefono) : anterior.telefono,
      email: dto.email !== undefined ? textoONull(dto.email) : anterior.email,
      empleado_id: dto.empleado_id !== undefined ? dto.empleado_id : anterior.empleado_id,
      actividad_ids: dto.actividad_ids ? idsUnicos(dto.actividad_ids) : anterior.actividad_ids,
      servicio_ids: dto.servicio_ids ? idsUnicos(dto.servicio_ids) : anterior.servicio_ids,
      sede_ids: dto.sede_ids ? idsUnicos(dto.sede_ids) : anterior.sede_ids,
      modalidad_pago: dto.modalidad_pago ?? anterior.modalidad_pago,
      tarifa: dto.tarifa !== undefined ? dto.tarifa : anterior.tarifa == null ? null : Number(anterior.tarifa),
    };
    lanzarSiHayErrores(erroresStaff(merged));
    await this.validarReferencias(empresa_id, merged);
    if (merged.ci !== anterior.ci) await this.validarCi(empresa_id, merged.ci, id);
    // Cambiar el rol deja colgados sus horarios (instructor) o sus turnos (profesional): relevamiento C 4.6#2.
    if (merged.tipo !== anterior.tipo) {
      if (anterior.tipo === gym_staff_tipo.INSTRUCTOR) {
        await exigirSinHorariosActivos(this.prisma, empresa_id, { instructor_id: id }, 'para cambiarle el rol, asigná esos horarios a otro instructor primero');
      } else {
        await this.exigirSinTurnos(id, empresa_id, 'cambiarle el rol');
      }
    }
    const staff = await this.prisma.gym_staff.update({
      where: { id },
      data: {
        ...merged,
        tarifa: merged.modalidad_pago === gym_modalidad_pago.FIJO ? null : merged.tarifa,
        updated_at: new Date(),
      },
      include: INCLUDE,
    });
    const limpio = this.sinPin(staff);
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'gym_staff',
      entity_id: id,
      old_value: this.sinPin(anterior),
      new_value: limpio,
    });
    return limpio;
  }

  private async exigirSinTurnos(id: string, empresa_id: string, accion: string) {
    const turnos = await this.prisma.gym_turno_items.count({
      // Turnos que todavía no empezaron (reservado o llegó) y no terminaron.
      where: { empresa_id, profesional_id: id, fin: { gte: new Date() }, turno: { estado: { in: [gym_turno_estado.RESERVADO, gym_turno_estado.LLEGO, gym_turno_estado.EN_CURSO] } } },
    });
    if (turnos)
      throw new ConflictException(
        `Para ${accion}: tiene ${turnos === 1 ? 'un turno reservado' : `${turnos} turnos reservados`}; cancelalos o reprogramalos primero (Turnos)`,
      );
  }

  async darDeBaja(id: string, empresa_id: string, user_id?: string) {
    const staff = await this.deEmpresa(id, empresa_id);
    if (!staff.activo) return this.sinPin(staff);
    await this.exigirSinTurnos(id, empresa_id, 'darlo de baja');
    await exigirSinHorariosActivos(this.prisma, empresa_id, { instructor_id: id }, 'asigná esos horarios a otro instructor primero');
    const baja = await this.prisma.gym_staff.update({
      where: { id },
      data: { activo: false, updated_at: new Date() },
      include: INCLUDE,
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'ELIMINAR',
      entity_type: 'gym_staff',
      entity_id: id,
      old_value: this.sinPin(staff),
    });
    return this.sinPin(baja);
  }

  /**
   * Vuelve a habilitar a alguien dado de baja: la cédula no puede estar en otra persona activa y lo que tenía elegido
   * (actividades, servicios, sedes) tiene que seguir activo.
   */
  async reactivar(id: string, empresa_id: string, user_id?: string) {
    const staff = await this.deEmpresa(id, empresa_id);
    if (staff.activo) return this.sinPin(staff);
    await this.validarCi(empresa_id, staff.ci, id);
    await this.validarReferencias(empresa_id, staff);
    const alta = await this.prisma.gym_staff.update({ where: { id }, data: { activo: true, updated_at: new Date() }, include: INCLUDE });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'REACTIVAR',
      entity_type: 'gym_staff',
      entity_id: id,
      old_value: this.sinPin(staff),
      new_value: this.sinPin(alta),
    });
    return this.sinPin(alta);
  }
}
