import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { gym_reserva_canal, gym_reserva_estado, gym_sesion_estado, gym_socio_estado, Prisma } from '@prisma/client';
import { AuditService } from 'src/audit/audit.service';
import { PrismaService } from 'src/prisma/prisma.service';
import { aFecha, deFecha, diaPy, horaPy, sumarDias } from '../common/fechas-gym';
import { documentoDe } from '../common/socio-utils';
import { membresiaPlana } from '../socios/socios-gym.service';
import { ESTADOS_MEMBRESIA_FUERA } from '../ventas/gym-ventas.service';
import { cancelacionATiempo, elegibilidadReserva, fueraDeVentana, MembresiaReserva } from './clases-reglas';
import { HORIZONTE_DIAS, RESERVAS_VIVAS } from './horarios-gym.service';

const R = gym_reserva_estado;
const OCUPAN_LUGAR: gym_reserva_estado[] = [R.CONFIRMADA, R.ASISTIO];
const DIA_RE = /^\d{4}-\d{2}-\d{2}$/;
/** Máximo de días que se muestran (y generan) en una consulta de la agenda. */
const MAX_DIAS_AGENDA = 62;
/** La asistencia se marca desde 90 min antes del inicio: la misma ventana que toma el ingreso por recepción. */
const ASISTENCIA_ANTES_MS = 90 * 60_000;

type Tx = Prisma.TransactionClient;

const INCLUDE_SESION = {
  sede: { select: { id: true, nombre: true } },
  sala: { select: { id: true, nombre: true } },
  actividad: { select: { id: true, nombre: true, color: true, tipo: true } },
  instructor: { select: { id: true, nombre: true } },
} satisfies Prisma.gym_sesionesInclude;

function sesionPlana<T extends { dia: Date; inicio: Date; fin: Date }>(s: T) {
  return { ...s, dia: deFecha(s.dia), hora_inicio: horaPy(s.inicio), hora_fin: horaPy(s.fin) };
}

/**
 * Agenda de clases y reservas (docs/plan-gimnasio.md §6 y §15.9). El cupo se
 * controla con la fila de la sesión bloqueada (FOR UPDATE): dos recepciones a la
 * vez no sobrevenden el último lugar. Los créditos se descuentan al confirmar y
 * se devuelven si se cancela a tiempo.
 */
@Injectable()
export class ReservasGymService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
  ) {}

  private async config(empresa_id: string) {
    return this.prisma.gym_config.upsert({ where: { empresa_id }, create: { empresa_id }, update: {} });
  }

  async agenda(empresa_id: string, f: { desde?: string; hasta?: string; sede_id?: string }) {
    const desde = f.desde && DIA_RE.test(f.desde) ? f.desde : diaPy();
    let hasta = f.hasta && DIA_RE.test(f.hasta) ? f.hasta : sumarDias(desde, 6);
    if (hasta < desde) throw new BadRequestException('La fecha hasta no puede ser anterior a la fecha desde');
    if (hasta > sumarDias(desde, MAX_DIAS_AGENDA)) hasta = sumarDias(desde, MAX_DIAS_AGENDA);
    // Leer no genera (relevamiento C 1.6#6: una lectura escribía con permiso de lectura). Las sesiones las crean el alta y
    // la edición del horario y el cron diario, HORIZONTE_DIAS hacia adelante; más allá la pantalla avisa que todavía no
    // están publicadas.
    const sesiones = await this.prisma.gym_sesiones.findMany({
      where: { empresa_id, dia: { gte: aFecha(desde), lte: aFecha(hasta) }, ...(f.sede_id && { sede_id: f.sede_id }) },
      include: {
        ...INCLUDE_SESION,
        gym_reservas: { where: { estado: { in: RESERVAS_VIVAS } }, select: { estado: true } },
      },
      orderBy: { inicio: 'asc' },
    });
    return {
      desde,
      hasta,
      generado_hasta: sumarDias(diaPy(), HORIZONTE_DIAS),
      sesiones: sesiones.map(({ gym_reservas, ...s }) => ({
        ...sesionPlana(s),
        confirmadas: gym_reservas.filter((r) => OCUPAN_LUGAR.includes(r.estado)).length,
        en_espera: gym_reservas.filter((r) => r.estado === R.LISTA_ESPERA).length,
        asistieron: gym_reservas.filter((r) => r.estado === R.ASISTIO).length,
      })),
    };
  }

  async sesion(id: string, empresa_id: string) {
    const s = await this.prisma.gym_sesiones.findFirst({
      where: { id, empresa_id },
      include: {
        ...INCLUDE_SESION,
        gym_reservas: {
          where: { estado: { not: R.CANCELADA } },
          include: {
            socio: {
              select: {
                id: true,
                numero_socio: true,
                cliente: {
                  select: { personas: { select: { razon_social: true, nro_documento: true, ruc: true, dv: true } } },
                },
              },
            },
            membresia: { select: { plan: { select: { nombre: true } } } },
          },
          orderBy: [{ posicion_espera: { sort: 'asc', nulls: 'first' } }, { created_at: 'asc' }],
        },
      },
    });
    if (!s) throw new NotFoundException('No se encontró la clase');
    const { gym_reservas, ...resto } = s;
    return {
      ...sesionPlana(resto),
      confirmadas: gym_reservas.filter((r) => OCUPAN_LUGAR.includes(r.estado)).length,
      reservas: gym_reservas.map((r) => ({
        id: r.id,
        estado: r.estado,
        posicion_espera: r.posicion_espera,
        credito_consumido: r.credito_consumido,
        canal: r.canal,
        plan: r.membresia?.plan.nombre ?? null,
        created_at: r.created_at,
        socio: {
          id: r.socio.id,
          numero_socio: r.socio.numero_socio,
          nombre: r.socio.cliente.personas?.razon_social ?? '',
          documento: documentoDe(r.socio.cliente.personas),
        },
      })),
    };
  }

  /** Cancela la clase: todas las reservas vivas quedan canceladas y los créditos vuelven. */
  async cancelarSesion(id: string, motivo: string, empresa_id: string, user_id?: string) {
    const r = await this.prisma.$transaction(async (tx) => {
      const s = await this.bloquearSesion(tx, id, empresa_id);
      if (s.estado !== gym_sesion_estado.PROGRAMADA)
        throw new BadRequestException('La clase ya está cancelada o dictada');
      const vivas = await tx.gym_reservas.findMany({
        where: { empresa_id, sesion_id: id, estado: { in: [R.CONFIRMADA, R.LISTA_ESPERA] } },
      });
      for (const v of vivas) await this.devolverCredito(tx, empresa_id, v);
      await tx.gym_reservas.updateMany({
        where: { empresa_id, sesion_id: id, estado: { in: [R.CONFIRMADA, R.LISTA_ESPERA] } },
        data: {
          estado: R.CANCELADA,
          cancelada_at: new Date(),
          posicion_espera: null,
          credito_consumido: false,
          updated_at: new Date(),
        },
      });
      await tx.gym_sesiones.update({
        where: { id },
        data: {
          estado: gym_sesion_estado.CANCELADA,
          motivo_cancelacion: motivo.trim(),
          cancelada_at: new Date(),
          cancelada_por: user_id ?? null,
          updated_at: new Date(),
        },
      });
      return vivas.length;
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'gym_sesiones',
      entity_id: id,
      descripcion: `Clase cancelada: ${motivo.trim()}`.slice(0, 255),
      new_value: { reservas_canceladas: r },
    });
    return { ok: true, reservas_canceladas: r };
  }

  private async bloquearSesion(tx: Tx, id: string, empresa_id: string) {
    const filas = await tx.$queryRaw<
      Array<{ id: string }>
    >`SELECT id FROM gym_sesiones WHERE id = ${id}::uuid AND empresa_id = ${empresa_id}::uuid FOR UPDATE`;
    if (!filas.length) throw new NotFoundException('No se encontró la clase');
    const s = await tx.gym_sesiones.findFirst({
      where: { id, empresa_id },
      include: { actividad: { select: { id: true, nombre: true } } },
    });
    if (!s) throw new NotFoundException('No se encontró la clase');
    return s;
  }

  private async membresias(tx: Tx, empresa_id: string, socio_id: string): Promise<MembresiaReserva[]> {
    const ms = await tx.gym_membresias.findMany({
      where: { empresa_id, socio_id, estado: { notIn: ESTADOS_MEMBRESIA_FUERA } },
      include: {
        plan: {
          select: {
            nombre: true,
            tipo: true,
            alcance_sedes: true,
            sedes_permitidas: true,
            hora_desde: true,
            hora_hasta: true,
            actividades_incluidas: true,
            creditos_actividades: true,
          },
        },
      },
    });
    return ms.map(membresiaPlana);
  }

  /** Descuenta un crédito sólo si queda saldo (atómico). */
  private async consumirCredito(tx: Tx, empresa_id: string, membresia_id: string): Promise<boolean> {
    const n = await tx.$executeRaw`
      UPDATE gym_membresias SET creditos_usados = creditos_usados + 1, updated_at = now()
      WHERE id = ${membresia_id}::uuid AND empresa_id = ${empresa_id}::uuid
        AND creditos_totales IS NOT NULL AND creditos_usados < creditos_totales`;
    return n > 0;
  }

  private async devolverCredito(
    tx: Tx,
    empresa_id: string,
    r: { membresia_id: string | null; credito_consumido: boolean },
  ) {
    if (!r.credito_consumido || !r.membresia_id) return;
    await tx.$executeRaw`
      UPDATE gym_membresias SET creditos_usados = GREATEST(creditos_usados - 1, 0), updated_at = now()
      WHERE id = ${r.membresia_id}::uuid AND empresa_id = ${empresa_id}::uuid`;
  }

  /** Con N faltas en 30 días, no reserva por X días (apagado por defecto: max_no_show_30d = 0). */
  private async bloqueadoPorFaltas(
    tx: Tx,
    empresa_id: string,
    socio_id: string,
    cfg: { max_no_show_30d: number; dias_bloqueo_reserva: number },
  ) {
    if (!cfg.max_no_show_30d) return null;
    const faltas = await tx.gym_reservas.findMany({
      where: { empresa_id, socio_id, estado: R.NO_SHOW, updated_at: { gte: new Date(Date.now() - 30 * 86_400_000) } },
      select: { updated_at: true },
      orderBy: { updated_at: 'desc' },
    });
    if (faltas.length < cfg.max_no_show_30d) return null;
    const hasta = new Date((faltas[0].updated_at ?? new Date()).getTime() + cfg.dias_bloqueo_reserva * 86_400_000);
    return hasta > new Date()
      ? `Tiene ${faltas.length} faltas en 30 días: no puede reservar hasta el ${diaPy(hasta).split('-').reverse().join('/')}`
      : null;
  }

  async reservar(
    sesion_id: string,
    socio_id: string,
    empresa_id: string,
    user_id?: string,
    canal: gym_reserva_canal = gym_reserva_canal.RECEPCION,
  ) {
    const cfg = await this.config(empresa_id);
    const res = await this.prisma.$transaction(async (tx) => {
      const s = await this.bloquearSesion(tx, sesion_id, empresa_id);
      if (s.estado !== gym_sesion_estado.PROGRAMADA)
        throw new BadRequestException('La clase está cancelada o ya se dictó');
      if (s.fin.getTime() < Date.now()) throw new BadRequestException('La clase ya terminó');
      const fuera = fueraDeVentana(s.inicio, new Date(), cfg.ventana_reserva_horas);
      if (fuera) throw new BadRequestException(fuera);
      const socio = await tx.gym_socios.findFirst({
        where: { id: socio_id, empresa_id },
        select: { id: true, estado: true, numero_socio: true, sede_base_id: true },
      });
      if (!socio) throw new NotFoundException('No se encontró el socio');
      if (socio.estado !== gym_socio_estado.ACTIVO)
        throw new BadRequestException(
          socio.estado === gym_socio_estado.BAJA ? 'El socio está dado de baja' : 'El socio está suspendido',
        );
      const ya = await tx.gym_reservas.findFirst({
        where: { empresa_id, sesion_id, socio_id, estado: { not: R.CANCELADA } },
        select: { estado: true },
      });
      if (ya)
        throw new ConflictException(
          ya.estado === R.LISTA_ESPERA
            ? 'Ya está en la lista de espera de esta clase'
            : 'Ya tiene reservada esta clase',
        );
      const bloqueo = await this.bloqueadoPorFaltas(tx, empresa_id, socio_id, cfg);
      if (bloqueo) throw new BadRequestException(bloqueo);

      const el = elegibilidadReserva({
        membresias: await this.membresias(tx, empresa_id, socio_id),
        actividad: s.actividad,
        dia: deFecha(s.dia),
        sedeId: s.sede_id,
        sedeBaseSocio: socio.sede_base_id,
      });
      if (!el.ok) throw new BadRequestException(el.mensaje);

      const ocupados = await tx.gym_reservas.count({ where: { empresa_id, sesion_id, estado: { in: OCUPAN_LUGAR } } });
      if (ocupados < s.cupo) {
        if (el.consume_credito && !(await this.consumirCredito(tx, empresa_id, el.membresia_id)))
          throw new BadRequestException('No le quedan créditos');
        const r = await tx.gym_reservas.create({
          data: {
            empresa_id,
            sesion_id,
            socio_id,
            membresia_id: el.membresia_id,
            estado: R.CONFIRMADA,
            canal,
            credito_consumido: el.consume_credito,
            usuario_id: user_id ?? null,
          },
        });
        return { reserva: r, mensaje: el.mensaje, lugares_libres: s.cupo - ocupados - 1 };
      }
      const ultimo = await tx.gym_reservas.aggregate({
        where: { empresa_id, sesion_id, estado: R.LISTA_ESPERA },
        _max: { posicion_espera: true },
      });
      const posicion = (ultimo._max.posicion_espera ?? 0) + 1;
      const r = await tx.gym_reservas.create({
        data: {
          empresa_id,
          sesion_id,
          socio_id,
          membresia_id: el.membresia_id,
          estado: R.LISTA_ESPERA,
          posicion_espera: posicion,
          canal,
          usuario_id: user_id ?? null,
        },
      });
      return {
        reserva: r,
        mensaje: `Clase llena: queda N° ${posicion} en la lista de espera${el.consume_credito ? ' (el crédito se descuenta si entra)' : ''}`,
        lugares_libres: 0,
      };
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'CREAR',
      entity_type: 'gym_reservas',
      entity_id: res.reserva.id,
      descripcion: `Reserva ${res.reserva.estado}`,
      new_value: { sesion_id, socio_id, estado: res.reserva.estado },
    });
    return {
      id: res.reserva.id,
      estado: res.reserva.estado,
      posicion_espera: res.reserva.posicion_espera,
      mensaje: res.mensaje,
      lugares_libres: res.lugares_libres,
    };
  }

  /**
   * Primero de la lista de espera que siga pudiendo reservar (con saldo, si usa
   * créditos) pasa a confirmado. Devuelve su nombre para avisarle.
   */
  private async promoverEspera(
    tx: Tx,
    empresa_id: string,
    sesion: { id: string; cupo: number; dia: Date; sede_id: string; actividad: { id: string; nombre: string } },
  ) {
    const ocupados = await tx.gym_reservas.count({
      where: { empresa_id, sesion_id: sesion.id, estado: { in: OCUPAN_LUGAR } },
    });
    if (ocupados >= sesion.cupo) return null;
    const espera = await tx.gym_reservas.findMany({
      where: { empresa_id, sesion_id: sesion.id, estado: R.LISTA_ESPERA },
      include: {
        socio: {
          select: {
            estado: true,
            sede_base_id: true,
            cliente: { select: { personas: { select: { razon_social: true } } } },
          },
        },
      },
      orderBy: { posicion_espera: 'asc' },
    });
    for (const r of espera) {
      if (r.socio.estado !== gym_socio_estado.ACTIVO) continue;
      const el = elegibilidadReserva({
        membresias: await this.membresias(tx, empresa_id, r.socio_id),
        actividad: sesion.actividad,
        dia: deFecha(sesion.dia),
        sedeId: sesion.sede_id,
        sedeBaseSocio: r.socio.sede_base_id,
      });
      if (!el.ok) continue;
      if (el.consume_credito && !(await this.consumirCredito(tx, empresa_id, el.membresia_id))) continue;
      await tx.gym_reservas.update({
        where: { id: r.id },
        data: {
          estado: R.CONFIRMADA,
          posicion_espera: null,
          membresia_id: el.membresia_id,
          credito_consumido: el.consume_credito,
          updated_at: new Date(),
        },
      });
      return r.socio.cliente.personas?.razon_social ?? '';
    }
    return null;
  }

  async cancelarReserva(id: string, empresa_id: string, user_id?: string) {
    const cfg = await this.config(empresa_id);
    const res = await this.prisma.$transaction(async (tx) => {
      const r0 = await tx.gym_reservas.findFirst({ where: { id, empresa_id }, select: { sesion_id: true } });
      if (!r0) throw new NotFoundException('No se encontró la reserva');
      const s = await this.bloquearSesion(tx, r0.sesion_id, empresa_id);
      const r = await tx.gym_reservas.findFirst({ where: { id, empresa_id } });
      if (!r) throw new NotFoundException('No se encontró la reserva');
      if (r.estado !== R.CONFIRMADA && r.estado !== R.LISTA_ESPERA)
        throw new BadRequestException('Sólo se cancela una reserva confirmada o en espera');
      const aTiempo = cancelacionATiempo(s.inicio, new Date(), cfg.horas_cancelacion_sin_penalidad);
      const devuelve = r.estado === R.CONFIRMADA && r.credito_consumido && aTiempo;
      if (devuelve) await this.devolverCredito(tx, empresa_id, r);
      await tx.gym_reservas.update({
        where: { id },
        data: {
          estado: R.CANCELADA,
          cancelada_at: new Date(),
          posicion_espera: null,
          cancelacion_tardia: r.estado === R.CONFIRMADA && !aTiempo,
          credito_consumido: r.credito_consumido && !devuelve,
          updated_at: new Date(),
        },
      });
      const promovido =
        r.estado === R.CONFIRMADA && s.estado === gym_sesion_estado.PROGRAMADA
          ? await this.promoverEspera(tx, empresa_id, s)
          : null;
      return { aTiempo, devuelve, promovido, consumido: r.credito_consumido, confirmada: r.estado === R.CONFIRMADA };
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'gym_reservas',
      entity_id: id,
      descripcion: 'Reserva cancelada',
      new_value: res,
    });
    const partes = ['Reserva cancelada'];
    if (res.devuelve) partes.push('se devolvió el crédito');
    else if (res.consumido && res.confirmada && !res.aTiempo)
      partes.push(`canceló con menos de ${cfg.horas_cancelacion_sin_penalidad} h: el crédito no se devuelve`);
    if (res.promovido) partes.push(`entra ${res.promovido} desde la lista de espera`);
    return { ok: true, mensaje: partes.join('; '), credito_devuelto: res.devuelve, promovido: res.promovido };
  }

  async asistencia(id: string, asistio: boolean, empresa_id: string, user_id?: string) {
    const r = await this.prisma.gym_reservas.findFirst({
      where: { id, empresa_id },
      include: { sesion: { select: { inicio: true, estado: true } } },
    });
    if (!r) throw new NotFoundException('No se encontró la reserva');
    if (r.sesion.estado === gym_sesion_estado.CANCELADA) throw new BadRequestException('La clase está cancelada');
    if (!([R.CONFIRMADA, R.ASISTIO, R.NO_SHOW] as gym_reserva_estado[]).includes(r.estado))
      throw new BadRequestException('Sólo se marca la asistencia de una reserva confirmada');
    if (r.sesion.inicio.getTime() - ASISTENCIA_ANTES_MS > Date.now())
      throw new BadRequestException('La asistencia se marca desde una hora y media antes de la clase');
    const estado = asistio ? R.ASISTIO : R.NO_SHOW;
    await this.prisma.gym_reservas.update({
      where: { id },
      data: { estado, asistencia_at: asistio ? new Date() : null, updated_at: new Date() },
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'gym_reservas',
      entity_id: id,
      descripcion: asistio ? 'Asistió a la clase' : 'No vino a la clase',
    });
    return { ok: true, estado };
  }

  /**
   * Al entrar al gimnasio, las reservas confirmadas de clases que empiezan en la
   * próxima hora y media (o empezaron hace menos de una) quedan como asistidas.
   */
  async marcarPorIngreso(empresa_id: string, socio_id: string, ahora = new Date()) {
    const r = await this.prisma.gym_reservas.updateMany({
      where: {
        empresa_id,
        socio_id,
        estado: R.CONFIRMADA,
        sesion: {
          estado: gym_sesion_estado.PROGRAMADA,
          inicio: { gte: new Date(ahora.getTime() - 60 * 60_000), lte: new Date(ahora.getTime() + 90 * 60_000) },
        },
      },
      data: { estado: R.ASISTIO, asistencia_at: ahora, updated_at: ahora },
    });
    return r.count;
  }

  /** Reservas de hoy del socio, para la pantalla de recepción. */
  async delSocioHoy(empresa_id: string, socio_id: string, dia = diaPy()) {
    const filas = await this.prisma.gym_reservas.findMany({
      where: {
        empresa_id,
        socio_id,
        estado: { in: RESERVAS_VIVAS },
        sesion: { dia: aFecha(dia), estado: gym_sesion_estado.PROGRAMADA },
      },
      include: {
        sesion: {
          select: { inicio: true, actividad: { select: { nombre: true } }, sala: { select: { nombre: true } } },
        },
      },
      orderBy: { sesion: { inicio: 'asc' } },
    });
    return filas.map((r) => ({
      id: r.id,
      estado: r.estado,
      posicion_espera: r.posicion_espera,
      credito_consumido: r.credito_consumido,
      membresia_id: r.membresia_id,
      hora: horaPy(r.sesion.inicio),
      actividad: r.sesion.actividad.nombre,
      sala: r.sesion.sala?.nombre ?? null,
    }));
  }

  /** Próximas reservas del socio (ficha). */
  async proximasDelSocio(empresa_id: string, socio_id: string) {
    const filas = await this.prisma.gym_reservas.findMany({
      where: {
        empresa_id,
        socio_id,
        estado: { not: R.CANCELADA },
        sesion: { fin: { gte: new Date(Date.now() - 14 * 86_400_000) } },
      },
      include: { sesion: { include: INCLUDE_SESION } },
      orderBy: { sesion: { inicio: 'desc' } },
      take: 50,
    });
    return filas.map((r) => ({
      id: r.id,
      estado: r.estado,
      posicion_espera: r.posicion_espera,
      credito_consumido: r.credito_consumido,
      sesion: sesionPlana(r.sesion),
    }));
  }

  /**
   * Cron: las clases que terminaron hace más de una hora pasan a DICTADA; las
   * reservas confirmadas sin asistencia, a NO_SHOW (el crédito no vuelve); la
   * lista de espera, a cancelada.
   */
  async cerrarPasadas(ahora = new Date()): 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 limite = new Date(ahora.getTime() - 60 * 60_000);
    const sesiones = await this.prisma.gym_sesiones.findMany({
      where: { empresa_id: { in: empresas }, estado: gym_sesion_estado.PROGRAMADA, fin: { lt: limite } },
      select: { id: true, empresa_id: true },
      take: 2000,
    });
    if (!sesiones.length) return 0;
    const ids = sesiones.map((s) => s.id);
    await this.prisma.$transaction([
      this.prisma.gym_reservas.updateMany({
        where: { empresa_id: { in: empresas }, sesion_id: { in: ids }, estado: R.CONFIRMADA },
        data: { estado: R.NO_SHOW, updated_at: ahora },
      }),
      this.prisma.gym_reservas.updateMany({
        where: { empresa_id: { in: empresas }, sesion_id: { in: ids }, estado: R.LISTA_ESPERA },
        data: { estado: R.CANCELADA, posicion_espera: null, cancelada_at: ahora, updated_at: ahora },
      }),
      this.prisma.gym_sesiones.updateMany({
        where: { empresa_id: { in: empresas }, id: { in: ids } },
        data: { estado: gym_sesion_estado.DICTADA, updated_at: ahora },
      }),
    ]);
    return ids.length;
  }
}
