import { Injectable, Logger } from '@nestjs/common';
import { gym_membresia_estado, gym_plan_tipo, gym_renovacion_desde, gym_servicio_modalidad, gym_socio_origen, gym_turno_estado, Prisma } from '@prisma/client';
import { AuditService } from 'src/audit/audit.service';
import { AlertasEmpresaService } from 'src/alertas-empresa/alertas-empresa.service';
import { alertaMembresiaSinCrear, claveMembresiaSinCrear } from '../common/alertas-gym';
import { PrismaService } from 'src/prisma/prisma.service';
import { aFecha, calcularVigencia, deFecha, diaPy } from '../common/fechas-gym';
import { ESTADOS_FACTURA_ANULADA, siguienteNumeroSocio } from '../common/socio-utils';

/** Membresías que ya no cuentan (para encadenar ni para entrar). */
export const ESTADOS_MEMBRESIA_FUERA = [gym_membresia_estado.ANULADA, gym_membresia_estado.REEMPLAZADA];

/**
 * Enganche del gimnasio con facturación (docs/plan-gimnasio.md §15.3).
 *
 * Lo llaman `FacturasService.create` (post-commit) y
 * `MiddlewareSifenService.revertirFacturaAnulada`. Sólo depende de Prisma y de
 * la auditoría (globales) para que esos módulos lo importen sin ciclos.
 *
 * Nunca lanza hacia la facturación: quien llama lo envuelve en try/catch, y acá
 * todo es idempotente (índice único por `factura_det_id`).
 */
@Injectable()
export class GymVentasService {
  private readonly logger = new Logger(GymVentasService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
    private readonly alertas: AlertasEmpresaService,
  ) {}

  /**
   * Crea las membresías de las líneas de planes de una factura recién emitida.
   * Para una empresa sin gimnasio cuesta una consulta y sale.
   */
  async procesarFactura(facturaId: string, empresaId: string, userId?: string | null): Promise<string[]> {
    const lineas = await this.prisma.factura_det.findMany({
      where: { factura_cab_id: facturaId },
      select: { id: true, producto_id: true, dcantproser: true, dtotopeitem: true },
      orderBy: { item: 'asc' },
    });
    if (!lineas.length) return [];
    // Spa: las líneas de servicios de turno marcan facturados los turnos realizados del cliente (plan v0.5 §6.1.5).
    await this.vincularTurnos(facturaId, empresaId, lineas);
    const planes = await this.prisma.gym_planes.findMany({
      where: { empresa_id: empresaId, activo: true, producto_id: { in: [...new Set(lineas.map((l) => l.producto_id))] } },
    });
    if (!planes.length) return [];

    const factura = await this.prisma.factura_cab.findFirst({
      where: { id: facturaId, empresa_id: empresaId },
      select: { id: true, cliente_id: true, dfeemide: true, dest: true, estado: true, moneda_id: true, created_at: true },
    });
    if (!factura || ESTADOS_FACTURA_ANULADA.includes(factura.estado ?? '')) return [];

    const planPorProducto = new Map(planes.map((p) => [p.producto_id, p]));
    // Un producto que ya se vendía antes de ser plan no genera membresías por esas ventas viejas.
    const pendientes = lineas.filter((l) => {
      const plan = planPorProducto.get(l.producto_id);
      return plan && (!plan.created_at || !factura.created_at || factura.created_at >= plan.created_at);
    });
    if (!pendientes.length) return [];
    const yaCreadas = new Set(
      (
        await this.prisma.gym_membresias.findMany({
          where: { empresa_id: empresaId, factura_det_id: { in: pendientes.map((l) => l.id) } },
          select: { factura_det_id: true },
        })
      ).map((m) => m.factura_det_id),
    );
    const aCrear = pendientes.filter((l) => !yaCreadas.has(l.id));
    if (!aCrear.length) return [];

    const config = await this.prisma.gym_config.findUnique({ where: { empresa_id: empresaId }, select: { renovacion_desde: true } });
    const sede = await this.sedeDeLaVenta(empresaId, factura.dest);
    const socio = await this.socioDelCliente(empresaId, factura.cliente_id, sede?.id ?? null, userId);
    // dfeemide se guarda como hora de Asunción sin zona (nowAsuncionNaive): el día es su parte UTC.
    const diaVenta = deFecha(factura.dfeemide);
    const hoy = diaPy();

    const creadas: string[] = [];
    for (const linea of aCrear) {
      const plan = planPorProducto.get(linea.producto_id);
      try {
        const anterior =
          plan.tipo === gym_plan_tipo.PERIODO || plan.tipo === gym_plan_tipo.MIXTO
            ? await this.prisma.gym_membresias.findFirst({
                where: {
                  empresa_id: empresaId,
                  socio_id: socio.id,
                  estado: { notIn: ESTADOS_MEMBRESIA_FUERA },
                  plan: { tipo: { in: [gym_plan_tipo.PERIODO, gym_plan_tipo.MIXTO] } },
                },
                orderBy: { fecha_fin: 'desc' },
                select: { id: true, fecha_fin: true },
              })
            : null;
        const v = calcularVigencia({
          plan,
          periodos: Number(linea.dcantproser),
          diaVenta,
          anteriorFin: anterior ? deFecha(anterior.fecha_fin) : null,
          renovacionDesde: config?.renovacion_desde ?? gym_renovacion_desde.FIN_ANTERIOR,
        });
        const membresia = await this.prisma.gym_membresias.create({
          data: {
            empresa_id: empresaId,
            socio_id: socio.id,
            plan_id: plan.id,
            sede_venta_id: sede?.id ?? null,
            sede_base_id: socio.sede_base_id ?? sede?.id ?? null,
            factura_id: factura.id,
            factura_det_id: linea.id,
            fecha_inicio: aFecha(v.fecha_inicio),
            fecha_fin: aFecha(v.fecha_fin),
            fecha_fin_original: aFecha(v.fecha_fin),
            estado: v.fecha_fin < hoy ? gym_membresia_estado.VENCIDA : gym_membresia_estado.ACTIVA,
            periodos: Math.max(1, Math.floor(Number(linea.dcantproser))),
            creditos_totales: v.creditos_totales,
            membresia_anterior_id: anterior?.id ?? null,
            precio_neto: linea.dtotopeitem,
            moneda_id: factura.moneda_id,
            created_by: userId ?? null,
          },
        });
        creadas.push(membresia.id);
        await this.audit.log({
          empresa_id: empresaId,
          user_id: userId ?? undefined,
          action: 'CREAR',
          entity_type: 'gym_membresias',
          entity_id: membresia.id,
          descripcion: `Membresía ${plan.nombre} del socio N° ${socio.numero_socio} por factura (${v.fecha_inicio} a ${v.fecha_fin})`,
          new_value: { factura_id: factura.id, plan: plan.nombre, fecha_inicio: v.fecha_inicio, fecha_fin: v.fecha_fin },
        });
      } catch (err) {
        // Otra llamada (el cron de reconciliación) la creó en paralelo: no es un error.
        if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') continue;
        throw err;
      }
    }
    return creadas;
  }

  /** Anula las membresías de una factura anulada o cancelada. Idempotente. */
  async anularPorFactura(facturaId: string, empresaId: string, motivo: string, usuarioId?: string | null): Promise<number> {
    await this.desvincularTurnos(facturaId, empresaId, usuarioId);
    const vivas = await this.prisma.gym_membresias.findMany({
      where: { factura_id: facturaId, empresa_id: empresaId, estado: { not: gym_membresia_estado.ANULADA } },
      select: { id: true, estado: true },
    });
    if (!vivas.length) return 0;
    const texto = `Factura anulada: ${motivo}`.slice(0, 500);
    await this.prisma.gym_membresias.updateMany({
      where: { empresa_id: empresaId, id: { in: vivas.map((m) => m.id) } },
      data: {
        estado: gym_membresia_estado.ANULADA,
        motivo_anulacion: texto,
        anulada_at: new Date(),
        anulada_por: usuarioId ?? null,
        updated_at: new Date(),
      },
    });
    for (const m of vivas) {
      await this.audit.log({
        empresa_id: empresaId,
        user_id: usuarioId ?? undefined,
        action: 'EDITAR',
        entity_type: 'gym_membresias',
        entity_id: m.id,
        descripcion: `Membresía anulada por anulación de la factura`,
        old_value: { estado: m.estado },
        new_value: { estado: gym_membresia_estado.ANULADA, motivo: texto },
      });
    }
    return vivas.length;
  }

  /**
   * Spa: cada línea de un servicio de turno se asigna a un ítem realizado, sin facturar ni cortesía, del mismo cliente y
   * producto (de ese día o anteriores): primero el de la misma cantidad, si no el más viejo. Un turno con todos sus
   * ítems asignados pasa a FACTURADO con el número de factura. Idempotente: una línea ya asignada no se vuelve a usar.
   */
  async vincularTurnos(
    facturaId: string,
    empresaId: string,
    lineas: Array<{ id: string; producto_id: string; dcantproser: Prisma.Decimal }>,
  ): Promise<number> {
    const productos = [...new Set(lineas.map((l) => l.producto_id))];
    const servicios = await this.prisma.gym_servicios.findMany({
      where: { empresa_id: empresaId, modalidad: gym_servicio_modalidad.TURNO, producto_id: { in: productos } },
      select: { producto_id: true },
    });
    if (!servicios.length) return 0;
    const factura = await this.prisma.factura_cab.findFirst({
      where: { id: facturaId, empresa_id: empresaId },
      select: { id: true, cliente_id: true, dfeemide: true, estado: true },
    });
    if (!factura?.cliente_id || ESTADOS_FACTURA_ANULADA.includes(factura.estado ?? '')) return 0;
    const deTurno = new Set(servicios.map((x) => x.producto_id));
    const ya = new Set(
      (await this.prisma.gym_turno_items.findMany({ where: { empresa_id: empresaId, factura_det_id: { in: lineas.map((l) => l.id) } }, select: { factura_det_id: true } })).map(
        (i) => i.factura_det_id,
      ),
    );
    const libres = lineas.filter((l) => deTurno.has(l.producto_id) && !ya.has(l.id));
    if (!libres.length) return 0;
    const candidatos = await this.prisma.gym_turno_items.findMany({
      where: {
        empresa_id: empresaId,
        factura_det_id: null,
        servicio: { producto_id: { in: [...new Set(libres.map((l) => l.producto_id))] } },
        turno: { cliente_id: factura.cliente_id, estado: gym_turno_estado.REALIZADO, cortesia: false, dia: { lte: aFecha(deFecha(factura.dfeemide)) } },
      },
      select: { id: true, turno_id: true, cantidad: true, cantidad_real: true, servicio: { select: { producto_id: true } } },
      orderBy: { inicio: 'asc' },
    });
    const usados = new Set<string>();
    const turnos = new Set<string>();
    for (const l of libres) {
      const mismos = candidatos.filter((c) => !usados.has(c.id) && c.servicio.producto_id === l.producto_id);
      const cantidad = (c: (typeof mismos)[number]) => Number(c.cantidad_real ?? c.cantidad);
      const elegido = mismos.find((c) => Math.abs(cantidad(c) - Number(l.dcantproser)) < 0.005) ?? mismos[0];
      if (!elegido) continue;
      const { count } = await this.prisma.gym_turno_items.updateMany({ where: { id: elegido.id, empresa_id: empresaId, factura_det_id: null }, data: { factura_det_id: l.id, updated_at: new Date() } });
      if (!count) continue;
      usados.add(elegido.id);
      turnos.add(elegido.turno_id);
    }
    for (const turno_id of turnos) {
      const pendientes = await this.prisma.gym_turno_items.count({ where: { empresa_id: empresaId, turno_id, factura_det_id: null } });
      if (pendientes) continue;
      await this.prisma.gym_turnos.updateMany({
        where: { id: turno_id, empresa_id: empresaId, estado: gym_turno_estado.REALIZADO },
        data: { estado: gym_turno_estado.FACTURADO, factura_id: facturaId, facturado_at: new Date(), updated_at: new Date() },
      });
      await this.audit.log({
        empresa_id: empresaId,
        action: 'EDITAR',
        entity_type: 'gym_turnos',
        entity_id: turno_id,
        descripcion: 'Turno facturado (la factura incluye sus servicios)',
        new_value: { estado: gym_turno_estado.FACTURADO, factura_id: facturaId },
      });
    }
    return usados.size;
  }

  /** Factura anulada (ECAN, cancelación local): sus turnos vuelven a «realizado – pendiente de cobro» (plan §6.1.5 punto 4). */
  async desvincularTurnos(facturaId: string, empresaId: string, usuarioId?: string | null): Promise<number> {
    const items = await this.prisma.gym_turno_items.findMany({
      where: { empresa_id: empresaId, factura_det: { factura_cab_id: facturaId } },
      select: { id: true, turno_id: true },
    });
    if (!items.length) return 0;
    await this.prisma.gym_turno_items.updateMany({
      where: { empresa_id: empresaId, id: { in: items.map((i) => i.id) } },
      data: { factura_det_id: null, updated_at: new Date() },
    });
    const turnos = [...new Set(items.map((i) => i.turno_id))];
    await this.prisma.gym_turnos.updateMany({
      where: { empresa_id: empresaId, id: { in: turnos }, estado: gym_turno_estado.FACTURADO },
      data: { estado: gym_turno_estado.REALIZADO, factura_id: null, facturado_at: null, updated_at: new Date() },
    });
    for (const id of turnos) {
      await this.audit.log({
        empresa_id: empresaId,
        user_id: usuarioId ?? undefined,
        action: 'EDITAR',
        entity_type: 'gym_turnos',
        entity_id: id,
        descripcion: 'Factura anulada: el turno vuelve a pendiente de cobro',
        new_value: { estado: gym_turno_estado.REALIZADO },
      });
    }
    return items.length;
  }

  /**
   * Red de seguridad del enganche: facturas recientes con líneas de planes y sin
   * membresía (backend reiniciado justo después de facturar, error transitorio).
   */
  async reconciliar(dias = 3, limite = 200): Promise<number> {
    const candidatas = await this.prisma.$queryRaw<Array<{ id: string; empresa_id: string; numero: string }>>`
      SELECT DISTINCT fc.id, fc.empresa_id, concat_ws('-', fc.dest, fc.dpunexp, fc.dnumdoc) AS numero
      FROM factura_det fd
      JOIN factura_cab fc ON fc.id = fd.factura_cab_id
      JOIN gym_planes gp ON gp.producto_id = fd.producto_id AND gp.empresa_id = fc.empresa_id AND gp.activo
      LEFT JOIN gym_membresias gm ON gm.factura_det_id = fd.id
      WHERE gm.id IS NULL
        AND fc.created_at >= now() - make_interval(days => ${dias}::int)
        AND fc.created_at >= gp.created_at
        AND coalesce(fc.estado, '') <> ALL(${ESTADOS_FACTURA_ANULADA})
      UNION
      -- Spa: líneas de servicios de turno sin ítem asignado, de un cliente con turnos realizados sin facturar.
      SELECT DISTINCT fc.id, fc.empresa_id, concat_ws('-', fc.dest, fc.dpunexp, fc.dnumdoc) AS numero
      FROM factura_det fd
      JOIN factura_cab fc ON fc.id = fd.factura_cab_id
      JOIN gym_servicios gs ON gs.producto_id = fd.producto_id AND gs.empresa_id = fc.empresa_id AND gs.modalidad = 'TURNO'
      WHERE NOT EXISTS (SELECT 1 FROM gym_turno_items i WHERE i.factura_det_id = fd.id)
        AND EXISTS (
          SELECT 1 FROM gym_turnos t JOIN gym_turno_items i ON i.turno_id = t.id
          WHERE t.empresa_id = fc.empresa_id AND t.cliente_id = fc.cliente_id AND t.estado = 'REALIZADO' AND NOT t.cortesia AND i.factura_det_id IS NULL)
        AND fc.created_at >= now() - make_interval(days => ${dias}::int)
        AND coalesce(fc.estado, '') <> ALL(${ESTADOS_FACTURA_ANULADA})
      LIMIT ${limite}::int`;
    let total = 0;
    for (const f of candidatas) {
      try {
        total += (await this.procesarFactura(f.id, f.empresa_id, null)).length;
        await this.alertas.resolver(f.empresa_id, claveMembresiaSinCrear(f.id), 'auto');
      } catch (err) {
        const error = (err as Error)?.message ?? String(err);
        this.logger.error(`Reconciliación: la factura ${f.id} no generó su membresía: ${error}`);
        // Sin la alerta, la falla solo estaba en el log: la empresa vendía un plan sin membresía y no se enteraba.
        await this.alertas.registrar(alertaMembresiaSinCrear({ empresaId: f.empresa_id, facturaId: f.id, numero: f.numero, error }));
      }
    }
    if (total) this.logger.warn(`Reconciliación: ${total} membresía(s) creadas que el enganche no había creado`);
    return total;
  }

  /** ACTIVA → VENCIDA para las que ya pasaron su fecha_fin (el acceso igual se decide por fechas). */
  async marcarVencidas(): Promise<number> {
    const empresas = (await this.prisma.gym_config.findMany({ select: { empresa_id: true } })).map((c) => c.empresa_id);
    if (!empresas.length) return 0;
    const r = await this.prisma.gym_membresias.updateMany({
      where: { empresa_id: { in: empresas }, estado: gym_membresia_estado.ACTIVA, fecha_fin: { lt: aFecha(diaPy()) } },
      data: { estado: gym_membresia_estado.VENCIDA, updated_at: new Date() },
    });
    return r.count;
  }

  /** La sede cuya sucursal tiene el establecimiento de la factura. */
  private sedeDeLaVenta(empresaId: string, dest: string) {
    return this.prisma.gym_sedes.findFirst({
      where: { empresa_id: empresaId, activo: true, sucursal: { punto_establecimiento: dest } },
      select: { id: true },
      orderBy: { created_at: 'asc' },
    });
  }

  /**
   * El socio del cliente; si todavía no es socio (le vendieron el plan sin pasar
   * por el alta), se crea con la ficha marcada como incompleta.
   */
  private async socioDelCliente(empresaId: string, clienteId: string, sedeId: string | null, userId?: string | null) {
    const existente = await this.prisma.gym_socios.findUnique({
      where: { empresa_id_cliente_id: { empresa_id: empresaId, cliente_id: clienteId } },
      select: { id: true, numero_socio: true, sede_base_id: true },
    });
    if (existente) return existente;
    const persona = await this.prisma.clientes.findUnique({
      where: { id: clienteId },
      select: { personas: { select: { email: true, celular: true, telefono: true } } },
    });
    try {
      const socio = await this.prisma.$transaction(async (tx) =>
        tx.gym_socios.create({
          data: {
            empresa_id: empresaId,
            cliente_id: clienteId,
            numero_socio: await siguienteNumeroSocio(tx, empresaId),
            email: persona?.personas?.email?.trim() || null,
            telefono: persona?.personas?.celular?.trim() || persona?.personas?.telefono?.trim() || null,
            sede_base_id: sedeId,
            origen: gym_socio_origen.VENTA,
            ficha_incompleta: true,
            created_by: userId ?? null,
          },
          select: { id: true, numero_socio: true, sede_base_id: true },
        }),
      );
      await this.audit.log({
        empresa_id: empresaId,
        user_id: userId ?? undefined,
        action: 'CREAR',
        entity_type: 'gym_socios',
        entity_id: socio.id,
        descripcion: `Socio N° ${socio.numero_socio} creado desde una venta (ficha incompleta)`,
      });
      return socio;
    } catch (err) {
      if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
        return this.prisma.gym_socios.findUniqueOrThrow({
          where: { empresa_id_cliente_id: { empresa_id: empresaId, cliente_id: clienteId } },
          select: { id: true, numero_socio: true, sede_base_id: true },
        });
      }
      throw err;
    }
  }
}
