import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import {
  gym_liquidacion_base as B,
  gym_liquidacion_estado as L,
  gym_staff_tipo,
  gym_turno_estado as E,
  Prisma,
} 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 { aFecha, deFecha, horaPy } from '../common/fechas-gym';
import { aPagar, decimalesDe } from '../turnos/spa-reglas';
import { documentoDe } from '../common/socio-utils';
import { CreateTarifaGymDto, PeriodoLiquidacionDto } from './dto/liquidaciones.dto';

const MAX_DIAS = 62;

/**
 * Liquidación de las profesionales del spa (plan v0.5 §6.1.6): cada ítem de turno con su servicio `paga_profesional`,
 * de la profesional, facturado (o cortesía si la empresa las paga) en el período, paga la tarifa vigente ese día
 * (monto × cantidad o % de lo facturado). Un ítem se liquida una vez: anular la liquidación lo libera.
 */
@Injectable()
export class LiquidacionesGymService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
  ) {}

  // ------------------------------------------------------------------ tarifas

  async tarifas(empresa_id: string, staff_id?: string) {
    return this.prisma.gym_staff_tarifas.findMany({
      where: { empresa_id, activo: true, ...(staff_id && { staff_id }) },
      include: { staff: { select: { id: true, nombre: true } }, servicio: { select: { id: true, nombre: true } } },
      orderBy: [{ staff_id: 'asc' }, { vigente_desde: 'desc' }],
    });
  }

  async crearTarifa(dto: CreateTarifaGymDto, empresa_id: string, user_id?: string) {
    if (dto.modo === 'PORCENTAJE' && dto.valor > 100) throw new BadRequestException('Un porcentaje va de 0 a 100');
    const staff = await this.prisma.gym_staff.findFirst({
      where: { id: dto.staff_id, empresa_id, activo: true },
      select: { id: true, tipo: true, nombre: true },
    });
    if (!staff) throw new BadRequestException('La profesional no existe o está dada de baja');
    if (staff.tipo !== gym_staff_tipo.PROFESIONAL)
      throw new BadRequestException(`${staff.nombre} es instructor: las tarifas son de las profesionales del spa`);
    if (dto.servicio_id) {
      const s = await this.prisma.gym_servicios.findFirst({
        where: { id: dto.servicio_id, empresa_id, activo: true },
        select: { id: true },
      });
      if (!s) throw new BadRequestException('El servicio no existe o está dado de baja');
    }
    const t = await this.prisma.gym_staff_tarifas.create({
      data: {
        empresa_id,
        staff_id: staff.id,
        servicio_id: dto.servicio_id ?? null,
        modo: dto.modo,
        valor: dto.valor,
        vigente_desde: aFecha(dto.vigente_desde),
        created_by: user_id ?? null,
      },
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'CREAR',
      entity_type: 'gym_staff_tarifas',
      entity_id: t.id,
      new_value: t,
    });
    return t;
  }

  async bajaTarifa(id: string, empresa_id: string, user_id?: string) {
    const t = await this.prisma.gym_staff_tarifas.findFirst({ where: { id, empresa_id } });
    if (!t) throw new NotFoundException('No se encontró la tarifa');
    if (!t.activo) return t;
    const baja = await this.prisma.gym_staff_tarifas.update({ where: { id }, data: { activo: false } });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'ELIMINAR',
      entity_type: 'gym_staff_tarifas',
      entity_id: id,
      old_value: t,
    });
    return baja;
  }

  // ------------------------------------------------------------------ liquidaciones

  async listar(empresa_id: string, f: { staff_id?: string; estado?: L } = {}) {
    return this.prisma.gym_liquidaciones.findMany({
      where: { empresa_id, ...(f.staff_id && { staff_id: f.staff_id }), ...(f.estado && { estado: f.estado }) },
      include: {
        staff: { select: { id: true, nombre: true } },
        moneda: { select: { codigo: true } },
        _count: { select: { items: true } },
      },
      orderBy: { desde: 'desc' },
      take: 200,
    });
  }

  async detalle(id: string, empresa_id: string) {
    const l = await this.prisma.gym_liquidaciones.findFirst({
      where: { id, empresa_id },
      include: {
        staff: { select: { id: true, nombre: true, ci: true } },
        moneda: { select: { codigo: true } },
        items: {
          include: {
            turno_item: {
              select: {
                inicio: true,
                servicio: { select: { nombre: true } },
                turno: {
                  select: {
                    dia: true,
                    cliente: {
                      select: {
                        personas: { select: { razon_social: true, nro_documento: true, ruc: true, dv: true } },
                      },
                    },
                  },
                },
              },
            },
          },
        },
      },
    });
    if (!l) throw new NotFoundException('No se encontró la liquidación');
    return {
      ...l,
      desde: deFecha(l.desde),
      hasta: deFecha(l.hasta),
      items: l.items
        .map((i) => ({
          id: i.id,
          fecha: deFecha(i.turno_item.turno.dia),
          hora: horaPy(i.turno_item.inicio),
          cliente: i.turno_item.turno.cliente.personas?.razon_social ?? '',
          documento: documentoDe(i.turno_item.turno.cliente.personas),
          servicio: i.turno_item.servicio.nombre,
          cantidad: Number(i.cantidad),
          importe_facturado: Number(i.importe_facturado),
          tarifa_modo: i.tarifa_modo,
          tarifa_valor: Number(i.tarifa_valor),
          a_pagar: Number(i.a_pagar),
        }))
        .sort((a, b) => `${a.fecha} ${a.hora}`.localeCompare(`${b.fecha} ${b.hora}`)),
    };
  }

  /** Lo que se liquidaría, sin guardar: para revisar antes de armarla. */
  previsualizar(dto: PeriodoLiquidacionDto, empresa_id: string) {
    return this.calcular(this.prisma, dto, empresa_id);
  }

  async crear(dto: PeriodoLiquidacionDto, empresa_id: string, user_id?: string) {
    const id = await this.prisma.$transaction(async (tx) => {
      // Una liquidación a la vez por profesional: dos que se arman juntas no toman el mismo ítem.
      await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`gym_liquidacion_${empresa_id}_${dto.staff_id}`}))`;
      const c = await this.calcular(tx, dto, empresa_id);
      if (c.sin_tarifa.length)
        throw new BadRequestException(
          `Falta la tarifa de ${c.staff.nombre} para ${[...new Set(c.sin_tarifa.map((x) => x.servicio))].join(', ')} (cargala en Tarifas)`,
        );
      if (!c.items.length) throw new BadRequestException('No hay servicios para liquidar en ese período');
      const l = await tx.gym_liquidaciones.create({
        data: {
          empresa_id,
          staff_id: dto.staff_id,
          desde: aFecha(dto.desde),
          hasta: aFecha(dto.hasta),
          base: dto.base ?? B.FECHA_SERVICIO,
          moneda_id: c.moneda?.id ?? null,
          total: c.total,
          created_by: user_id ?? null,
          items: {
            create: c.items.map((i) => ({
              empresa_id,
              turno_item_id: i.turno_item_id,
              cantidad: i.cantidad,
              importe_facturado: i.importe_facturado,
              tarifa_modo: i.tarifa_modo,
              tarifa_valor: i.tarifa_valor,
              a_pagar: i.a_pagar,
            })),
          },
        },
        select: { id: true },
      });
      return l.id;
    });
    const l = await this.detalle(id, empresa_id);
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'CREAR',
      entity_type: 'gym_liquidaciones',
      entity_id: id,
      descripcion: `Liquidación de ${l.staff.nombre} del ${l.desde} al ${l.hasta}`,
      new_value: { total: l.total, items: l.items.length },
    });
    return l;
  }

  async aprobar(id: string, empresa_id: string, user_id?: string) {
    return this.cambiarEstado(id, empresa_id, user_id, L.BORRADOR, L.APROBADA, {
      aprobada_por: user_id ?? null,
      aprobada_at: new Date(),
    });
  }

  async marcarPagada(id: string, empresa_id: string, user_id?: string) {
    return this.cambiarEstado(id, empresa_id, user_id, L.APROBADA, L.PAGADA, { pagada_at: new Date() });
  }

  async anular(id: string, motivo: string, empresa_id: string, user_id?: string) {
    const l = await this.prisma.gym_liquidaciones.findFirst({ where: { id, empresa_id }, select: { estado: true } });
    if (!l) throw new NotFoundException('No se encontró la liquidación');
    if (l.estado === L.ANULADA) throw new BadRequestException('La liquidación ya está anulada');
    if (l.estado === L.PAGADA)
      throw new BadRequestException('Ya está pagada: no se anula (registrá la devolución por fuera)');
    await this.prisma.$transaction([
      this.prisma.gym_liquidaciones.update({
        where: { id },
        data: { estado: L.ANULADA, motivo_anulacion: motivo.trim(), updated_at: new Date() },
      }),
      // Los ítems quedan libres para otra liquidación.
      this.prisma.gym_liquidacion_items.updateMany({
        where: { liquidacion_id: id, empresa_id },
        data: { activo: false },
      }),
    ]);
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'gym_liquidaciones',
      entity_id: id,
      old_value: { estado: l.estado },
      new_value: { estado: L.ANULADA, motivo },
    });
    return this.detalle(id, empresa_id);
  }

  // ------------------------------------------------------------------ internos

  private async cambiarEstado(
    id: string,
    empresa_id: string,
    user_id: string | undefined,
    desde: L,
    hacia: L,
    extra: Prisma.gym_liquidacionesUpdateInput,
  ) {
    const { count } = await this.prisma.gym_liquidaciones.updateMany({
      where: { id, empresa_id, estado: desde },
      data: { ...(extra as object), estado: hacia, updated_at: new Date() },
    });
    if (!count) {
      const l = await this.prisma.gym_liquidaciones.findFirst({ where: { id, empresa_id }, select: { estado: true } });
      if (!l) throw new NotFoundException('No se encontró la liquidación');
      throw new ConflictException(
        `La liquidación está ${l.estado.toLowerCase()}: no se puede pasar a ${hacia.toLowerCase()}`,
      );
    }
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'gym_liquidaciones',
      entity_id: id,
      old_value: { estado: desde },
      new_value: { estado: hacia },
    });
    return this.detalle(id, empresa_id);
  }

  private async calcular(db: Prisma.TransactionClient | PrismaService, dto: PeriodoLiquidacionDto, empresa_id: string) {
    if (dto.hasta < dto.desde) throw new BadRequestException('La fecha hasta no puede ser anterior a la fecha desde');
    const dias = (aFecha(dto.hasta).getTime() - aFecha(dto.desde).getTime()) / 86_400_000;
    if (dias > MAX_DIAS) throw new BadRequestException(`El período es de hasta ${MAX_DIAS} días`);
    const staff = await db.gym_staff.findFirst({
      where: { id: dto.staff_id, empresa_id },
      select: { id: true, nombre: true },
    });
    if (!staff) throw new NotFoundException('No se encontró la profesional');
    const [cfg, moneda] = await Promise.all([
      db.gym_config.findUnique({ where: { empresa_id }, select: { cortesia_paga_profesional: true } }),
      monedaBaseOpcional(db, empresa_id),
    ]);
    const base = dto.base ?? B.FECHA_SERVICIO;
    const desde = aFecha(dto.desde);
    const hasta = aFecha(dto.hasta);
    const pagaCortesia = cfg?.cortesia_paga_profesional ?? false;
    const items = await db.gym_turno_items.findMany({
      where: {
        empresa_id,
        profesional_id: staff.id,
        servicio: { paga_profesional: true },
        // Un ítem ya liquidado (en una liquidación no anulada) no vuelve a entrar.
        liquidaciones: { none: { activo: true } },
        OR: [
          {
            turno: { estado: E.FACTURADO, ...(base === B.FECHA_SERVICIO && { dia: { gte: desde, lte: hasta } }) },
            ...(base === B.FECHA_FACTURA && {
              factura_det: { factura_cab: { dfeemide: { gte: desde, lt: new Date(hasta.getTime() + 86_400_000) } } },
            }),
          },
          ...(pagaCortesia
            ? [{ turno: { estado: E.REALIZADO, cortesia: true, dia: { gte: desde, lte: hasta } } }]
            : []),
        ],
      },
      include: {
        servicio: { select: { id: true, nombre: true } },
        factura_det: { select: { dtotopeitem: true } },
        turno: {
          select: { dia: true, cortesia: true, cliente: { select: { personas: { select: { razon_social: true } } } } },
        },
      },
      orderBy: { inicio: 'asc' },
    });
    const tarifas = await db.gym_staff_tarifas.findMany({
      where: { empresa_id, staff_id: staff.id, activo: true },
      orderBy: { vigente_desde: 'desc' },
    });
    const decimales = decimalesDe(moneda?.codigo);
    const filas: Array<{
      turno_item_id: string;
      fecha: string;
      cliente: string;
      servicio: string;
      cantidad: number;
      importe_facturado: number;
      tarifa_modo: (typeof tarifas)[number]['modo'];
      tarifa_valor: number;
      a_pagar: number;
      cortesia: boolean;
    }> = [];
    const sinTarifa: Array<{ turno_item_id: string; servicio: string }> = [];
    for (const i of items) {
      const dia = i.turno.dia;
      // La tarifa vigente ese día: la del servicio, si no la general de la profesional.
      const t =
        tarifas.find((x) => x.servicio_id === i.servicio_id && x.vigente_desde <= dia) ??
        tarifas.find((x) => x.servicio_id === null && x.vigente_desde <= dia);
      if (!t) {
        sinTarifa.push({ turno_item_id: i.id, servicio: i.servicio.nombre });
        continue;
      }
      const cantidad = Number(i.cantidad_real ?? i.cantidad);
      const facturado = i.factura_det ? Number(i.factura_det.dtotopeitem) : 0;
      filas.push({
        turno_item_id: i.id,
        fecha: deFecha(dia),
        cliente: i.turno.cliente.personas?.razon_social ?? '',
        servicio: i.servicio.nombre,
        cantidad,
        importe_facturado: facturado,
        tarifa_modo: t.modo,
        tarifa_valor: Number(t.valor),
        a_pagar: aPagar(t, cantidad, facturado, decimales).toNumber(),
        cortesia: i.turno.cortesia,
      });
    }
    const total = filas
      .reduce((s, f) => s.plus(f.a_pagar), new Prisma.Decimal(0))
      .toDecimalPlaces(decimales)
      .toNumber();
    return { staff, moneda, base, desde: dto.desde, hasta: dto.hasta, items: filas, sin_tarifa: sinTarifa, total };
  }
}
