import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import {
  gym_sala_tipo,
  gym_servicio_modalidad,
  gym_staff_tipo,
  gym_turno_canal,
  gym_turno_estado as E,
  Prisma,
} from '@prisma/client';
import { AuditService } from 'src/audit/audit.service';
import { ListaPreciosService } from 'src/lista-precios/lista-precios.service';
import { PrismaService } from 'src/prisma/prisma.service';
import { monedaBaseOpcional } from 'src/utils/montos-moneda';
import { diaSemanaIso, instanteDe } from '../clases/clases-reglas';
import { aFecha, deFecha, diaPy, horaPy } from '../common/fechas-gym';
import { textoONull } from '../common/gym-utils';
import { documentoDe } from '../common/socio-utils';
import { CreateTurnoGymDto, ItemTurnoDto, UpdateItemTurnoDto, UpdateTurnoGymDto } from './dto/turnos.dto';
import {
  choqueDeRecurso,
  decimalesDe,
  duracionDe,
  errorCantidad,
  errorHorario,
  errorTransicion,
  finDe,
  horarioDelDia,
  TURNOS_QUE_OCUPAN,
} from './spa-reglas';

const DIA_RE = /^\d{4}-\d{2}-\d{2}$/;
/** Llegó / en curso / realizado / no vino se marca desde 90 min antes del inicio, como la asistencia a clases. */
const MARCAR_ANTES_MS = 90 * 60_000;
/** Recursos del spa (las columnas de la agenda): todo lo que no es una sala de clases. */
const RECURSOS_SPA: gym_sala_tipo[] = [gym_sala_tipo.CABINA, gym_sala_tipo.HIDROMASAJE, gym_sala_tipo.SAUNA];

type Tx = Prisma.TransactionClient;

const INCLUDE_TURNO = {
  sede: { select: { id: true, nombre: true } },
  socio: { select: { id: true, numero_socio: true } },
  factura: { select: { id: true, dest: true, dpunexp: true, dnumdoc: true } },
  cliente: {
    select: {
      id: true,
      personas: {
        select: { razon_social: true, nro_documento: true, ruc: true, dv: true, celular: true, telefono: true },
      },
    },
  },
  items: {
    orderBy: { orden: 'asc' },
    include: {
      servicio: {
        select: {
          id: true,
          nombre: true,
          producto_id: true,
          unidad_tiempo_min: true,
          duracion_min: true,
          requiere_profesional: true,
          paga_profesional: true,
        },
      },
      sala: { select: { id: true, nombre: true, tipo: true } },
      profesional: { select: { id: true, nombre: true } },
      factura_det: { select: { id: true, dtotopeitem: true } },
    },
  },
} satisfies Prisma.gym_turnosInclude;

type TurnoConRelaciones = Prisma.gym_turnosGetPayload<{ include: typeof INCLUDE_TURNO }>;
type Precio = { monto: number; moneda: string | null; error: string | null };
/** Precios de la lista por `${cliente}|${producto}`: el importe del turno se calcula, nunca se guarda (regla 1 del módulo). */
type Precios = Map<string, Precio>;

const unidadDe = (s: { unidad_tiempo_min: number | null; duracion_min: number | null }) =>
  s.unidad_tiempo_min ?? s.duracion_min ?? 60;
const num = (d: Prisma.Decimal | number | null | undefined) => (d == null ? null : Number(d));

/**
 * El spa (plan v0.5 §6.1): la agenda que reemplaza al cuaderno. Un turno es un cliente del ERP en un día con uno o más
 * servicios encadenados; cada servicio ocupa un recurso (cabina, hidromasaje) y, si lleva, una profesional. La
 * superposición se verifica con un lock por empresa y día, en la misma transacción que el alta o el cambio.
 */
@Injectable()
export class TurnosGymService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
    private readonly listaPrecios: ListaPreciosService,
  ) {}

  // ------------------------------------------------------------------ lectura

  /** La agenda de un día: recursos (columnas), horario, bloque, servicios con su precio de lista y los turnos. */
  async agenda(empresa_id: string, f: { dia?: string; sede_id?: string }) {
    const dia = f.dia && DIA_RE.test(f.dia) ? f.dia : diaPy();
    const sede = await this.sede(this.prisma, empresa_id, f.sede_id, true);
    const [cfg, moneda, turnos, staff, recursos, servicios] = await Promise.all([
      this.prisma.gym_config.upsert({ where: { empresa_id }, create: { empresa_id }, update: {} }),
      monedaBaseOpcional(this.prisma, empresa_id),
      sede
        ? this.prisma.gym_turnos.findMany({
            where: { empresa_id, sede_id: sede.id, dia: aFecha(dia), estado: { not: E.CANCELADO } },
            include: INCLUDE_TURNO,
            orderBy: { inicio: 'asc' },
          })
        : [],
      this.prisma.gym_staff.findMany({
        where: { empresa_id, activo: true, tipo: gym_staff_tipo.PROFESIONAL },
        select: { id: true, nombre: true, servicio_ids: true, sede_ids: true },
        orderBy: { nombre: 'asc' },
      }),
      sede
        ? this.prisma.gym_salas.findMany({
            where: { empresa_id, sede_id: sede.id, activo: true, tipo: { in: RECURSOS_SPA } },
            select: { id: true, nombre: true, tipo: true, capacidad: true },
            orderBy: [{ tipo: 'asc' }, { nombre: 'asc' }],
          })
        : [],
      this.prisma.gym_servicios.findMany({
        where: { empresa_id, activo: true, modalidad: gym_servicio_modalidad.TURNO },
        select: {
          id: true,
          nombre: true,
          duracion_min: true,
          unidad_tiempo_min: true,
          fraccion_minima: true,
          requiere_profesional: true,
          paga_profesional: true,
          habilita_acceso_dia: true,
          sala_ids: true,
          producto_id: true,
        },
        orderBy: { nombre: 'asc' },
      }),
    ]);
    const base = moneda?.codigo ?? null;
    // Precio de lista (sin cliente) para el catálogo, y el de cada cliente para sus turnos.
    const precios: Precios = new Map();
    await this.cargarPrecios(
      empresa_id,
      precios,
      null,
      servicios.map((s) => s.producto_id),
      base,
    );
    for (const cliente_id of new Set(turnos.map((t) => t.cliente_id)))
      await this.cargarPrecios(
        empresa_id,
        precios,
        cliente_id,
        turnos.filter((t) => t.cliente_id === cliente_id).flatMap((t) => t.items.map((i) => i.servicio.producto_id)),
        base,
      );

    const profesionales = staff
      .filter((s) => !sede || !s.sede_ids.length || s.sede_ids.includes(sede.id))
      .map((s) => ({ id: s.id, nombre: s.nombre, servicio_ids: s.servicio_ids }));
    // Quien tiene turnos ese día aparece aunque ya no sea profesional activa de la sede.
    for (const t of turnos)
      for (const i of t.items)
        if (i.profesional && !profesionales.some((p) => p.id === i.profesional!.id))
          profesionales.push({ ...i.profesional, servicio_ids: [] });

    const planos = turnos.map((t) => this.plano(t, precios, base));
    return {
      dia,
      sede,
      moneda,
      bloque_min: cfg.bloque_agenda_min,
      horario: horarioDelDia(cfg.horario_spa, diaSemanaIso(dia)) ?? null,
      horario_cargado: cfg.horario_spa != null,
      recursos: recursos.map((r) => ({ ...r, capacidad: r.capacidad ?? 1 })),
      profesionales,
      servicios: servicios.map((s) => ({
        ...s,
        fraccion_minima: Number(s.fraccion_minima),
        unidad_min: unidadDe(s),
        precio: precios.get(`-|${s.producto_id}`) ?? null,
      })),
      turnos: planos,
      totales: this.totales(planos, recursos),
    };
  }

  async turno(id: string, empresa_id: string) {
    const t = await this.prisma.gym_turnos.findFirst({ where: { id, empresa_id }, include: INCLUDE_TURNO });
    if (!t) throw new NotFoundException('No se encontró el turno');
    return this.planoConPrecios(empresa_id, t);
  }

  /** Próximos turnos de un cliente (ficha del socio o del cliente). */
  async proximosDelCliente(empresa_id: string, cliente_id: string) {
    const turnos = await this.prisma.gym_turnos.findMany({
      where: { empresa_id, cliente_id, fin: { gte: new Date() }, estado: { in: [E.RESERVADO, E.LLEGO, E.EN_CURSO] } },
      include: INCLUDE_TURNO,
      orderBy: { inicio: 'asc' },
      take: 20,
    });
    const base = (await monedaBaseOpcional(this.prisma, empresa_id))?.codigo ?? null;
    const precios: Precios = new Map();
    await this.cargarPrecios(
      empresa_id,
      precios,
      cliente_id,
      turnos.flatMap((t) => t.items.map((i) => i.servicio.producto_id)),
      base,
    );
    return turnos.map((t) => this.plano(t, precios, base));
  }

  /**
   * Lo realizado sin cobrar (no facturado ni cortesía), por cliente: lo que «Cobrar» lleva a la caja y lo que el cierre
   * de caja muestra como «Realizados sin facturar» (plan §6.1.5).
   */
  async pendientesDeCobro(empresa_id: string, f: { dia?: string; sede_id?: string; cliente_id?: string }) {
    const turnos = await this.prisma.gym_turnos.findMany({
      where: {
        empresa_id,
        estado: E.REALIZADO,
        cortesia: false,
        ...(f.dia && DIA_RE.test(f.dia) && { dia: aFecha(f.dia) }),
        ...(f.sede_id && { sede_id: f.sede_id }),
        ...(f.cliente_id && { cliente_id: f.cliente_id }),
      },
      include: INCLUDE_TURNO,
      orderBy: { inicio: 'asc' },
      take: 500,
    });
    const base = (await monedaBaseOpcional(this.prisma, empresa_id))?.codigo ?? null;
    const precios: Precios = new Map();
    for (const cliente_id of new Set(turnos.map((t) => t.cliente_id)))
      await this.cargarPrecios(
        empresa_id,
        precios,
        cliente_id,
        turnos.filter((t) => t.cliente_id === cliente_id).flatMap((t) => t.items.map((i) => i.servicio.producto_id)),
        base,
      );
    const porCliente = new Map<string, ReturnType<TurnosGymService['plano']>[]>();
    for (const t of turnos)
      porCliente.set(t.cliente_id, [...(porCliente.get(t.cliente_id) ?? []), this.plano(t, precios, base)]);
    return [...porCliente.values()].map((lista) => ({
      cliente: lista[0].cliente,
      turnos: lista,
      lineas: lista.flatMap((t) =>
        t.items
          .filter((i) => !i.facturado)
          .map((i) => ({
            item_id: i.id,
            producto_id: i.servicio.producto_id,
            descripcion: `${i.servicio.nombre} (${i.servicio.unidad_min} min)`,
            cantidad: i.cantidad_real ?? i.cantidad,
            importe_estimado: i.importe_estimado,
            moneda: i.moneda,
          })),
      ),
    }));
  }

  // ------------------------------------------------------------------ escritura

  async crear(dto: CreateTurnoGymDto, empresa_id: string, user_id?: string) {
    if (!dto.items[0]?.hora) throw new BadRequestException('Elegí la hora del primer servicio');
    const id = await this.prisma.$transaction(async (tx) => {
      const sede = await this.sede(tx, empresa_id, dto.sede_id, false);
      const cliente = await tx.clientes.findFirst({
        where: { id: dto.cliente_id, deleted: false, personas: { empresa_id } },
        select: { id: true },
      });
      if (!cliente) throw new BadRequestException('El cliente no existe en esta empresa');
      if (dto.dia < diaPy()) throw new BadRequestException('No se puede agendar en un día que ya pasó');
      await this.bloquearDia(tx, empresa_id, dto.dia);
      const filas = await this.ubicar(tx, empresa_id, sede, dto.dia, dto.items, [], 1);
      const socio = await tx.gym_socios.findFirst({
        where: { empresa_id, cliente_id: cliente.id },
        select: { id: true },
      });
      const t = await tx.gym_turnos.create({
        data: {
          empresa_id,
          sede_id: sede.id,
          cliente_id: cliente.id,
          socio_id: socio?.id ?? null,
          dia: aFecha(dto.dia),
          inicio: filas[0].inicio,
          fin: filas[filas.length - 1].fin,
          canal: dto.canal ?? gym_turno_canal.RECEPCION,
          telefono_contacto: textoONull(dto.telefono_contacto),
          notas: textoONull(dto.notas),
          created_by: user_id ?? null,
          items: { create: filas.map((f) => ({ ...f, empresa_id })) },
        },
        select: { id: true },
      });
      return t.id;
    });
    const plano = await this.turno(id, empresa_id);
    await this.auditar(
      empresa_id,
      user_id,
      'CREAR',
      id,
      `Turno de ${plano.cliente.nombre} el ${plano.dia} ${plano.hora_inicio}: ${plano.items.map((i) => i.servicio.nombre).join(' + ')}`,
      undefined,
      plano,
    );
    return plano;
  }

  async actualizar(id: string, dto: UpdateTurnoGymDto, empresa_id: string, user_id?: string) {
    const a = await this.prisma.gym_turnos.findFirst({
      where: { id, empresa_id },
      select: { id: true, canal: true, telefono_contacto: true, notas: true, estado: true },
    });
    if (!a) throw new NotFoundException('No se encontró el turno');
    if (a.estado === E.CANCELADO) throw new BadRequestException('El turno está cancelado');
    await this.prisma.gym_turnos.update({
      where: { id },
      data: {
        ...(dto.canal && { canal: dto.canal }),
        ...(dto.telefono_contacto !== undefined && { telefono_contacto: textoONull(dto.telefono_contacto) }),
        ...(dto.notas !== undefined && { notas: textoONull(dto.notas) }),
        updated_at: new Date(),
      },
    });
    const t = await this.turno(id, empresa_id);
    await this.auditar(
      empresa_id,
      user_id,
      'EDITAR',
      id,
      `Turno de ${t.cliente.nombre}: datos de contacto o notas`,
      a,
      dto,
    );
    return t;
  }

  /** Encadenar otro servicio al turno (por defecto, al terminar el último). */
  async agregarItem(id: string, dto: ItemTurnoDto, empresa_id: string, user_id?: string) {
    await this.prisma.$transaction(async (tx) => {
      const t = await this.turnoEditable(tx, id, empresa_id);
      await this.bloquearDia(tx, empresa_id, deFecha(t.dia));
      const ultimo = t.items[t.items.length - 1];
      const item = { ...dto, hora: dto.hora ?? horaPy(ultimo.fin) };
      const [fila] = await this.ubicar(tx, empresa_id, t.sede, deFecha(t.dia), [item], [], ultimo.orden + 1);
      await tx.gym_turno_items.create({ data: { ...fila, empresa_id, turno_id: id } });
      await this.recalcularCabecera(tx, id);
    });
    const t = await this.turno(id, empresa_id);
    await this.auditar(
      empresa_id,
      user_id,
      'EDITAR',
      id,
      `Turno de ${t.cliente.nombre}: se agregó un servicio`,
      undefined,
      dto,
    );
    return t;
  }

  /** Mover (hora o recurso), estirar (cantidad), asignar profesional o corregir la cantidad real de un ítem. */
  async actualizarItem(item_id: string, dto: UpdateItemTurnoDto, empresa_id: string, user_id?: string) {
    const antes = await this.prisma.gym_turno_items.findFirst({
      where: { id: item_id, empresa_id },
      select: {
        id: true,
        turno_id: true,
        inicio: true,
        sala_id: true,
        cantidad: true,
        cantidad_real: true,
        profesional_id: true,
      },
    });
    if (!antes) throw new NotFoundException('No se encontró el servicio del turno');
    await this.prisma.$transaction(async (tx) => {
      const t = await tx.gym_turnos.findFirst({
        where: { id: antes.turno_id, empresa_id },
        select: { id: true, estado: true, dia: true, sede: { select: { id: true, nombre: true } } },
      });
      if (!t) throw new NotFoundException('No se encontró el turno');
      const soloReal =
        dto.cantidad_real !== undefined &&
        dto.hora === undefined &&
        dto.sala_id === undefined &&
        dto.cantidad === undefined &&
        dto.profesional_id === undefined;
      if (t.estado === E.FACTURADO || t.estado === E.CANCELADO || t.estado === E.NO_SHOW)
        throw new BadRequestException(
          t.estado === E.FACTURADO ? 'El turno ya está facturado' : 'El turno ya no se puede cambiar',
        );
      if (!soloReal && t.estado === E.REALIZADO && dto.profesional_id === undefined)
        throw new BadRequestException(
          'El turno ya se realizó: solo se le cambia la profesional o la cantidad que se hizo',
        );
      await this.bloquearDia(tx, empresa_id, deFecha(t.dia));
      const actual = await tx.gym_turno_items.findFirstOrThrow({
        where: { id: item_id, empresa_id },
        select: { servicio_id: true, orden: true },
      });
      const pedido: ItemTurnoDto = {
        servicio_id: actual.servicio_id,
        cantidad: dto.cantidad ?? Number(antes.cantidad),
        hora: dto.hora ?? horaPy(antes.inicio),
        sala_id: dto.sala_id !== undefined ? dto.sala_id : antes.sala_id,
        profesional_id: dto.profesional_id !== undefined ? dto.profesional_id : antes.profesional_id,
      };
      const [fila] = await this.ubicar(tx, empresa_id, t.sede, deFecha(t.dia), [pedido], [item_id], actual.orden);
      await tx.gym_turno_items.update({
        where: { id: item_id },
        data: {
          ...fila,
          ...(dto.cantidad_real !== undefined && { cantidad_real: dto.cantidad_real }),
          updated_at: new Date(),
        },
      });
      await this.recalcularCabecera(tx, t.id);
    });
    const t = await this.turno(antes.turno_id, empresa_id);
    await this.auditar(
      empresa_id,
      user_id,
      'EDITAR',
      antes.turno_id,
      `Turno de ${t.cliente.nombre}: cambió un servicio`,
      antes,
      dto,
    );
    return t;
  }

  async quitarItem(item_id: string, empresa_id: string, user_id?: string) {
    const item = await this.prisma.gym_turno_items.findFirst({
      where: { id: item_id, empresa_id },
      select: { id: true, turno_id: true },
    });
    if (!item) throw new NotFoundException('No se encontró el servicio del turno');
    await this.prisma.$transaction(async (tx) => {
      const t = await this.turnoEditable(tx, item.turno_id, empresa_id);
      if (t.items.length < 2)
        throw new BadRequestException('Es el único servicio del turno: para sacarlo, cancelá el turno');
      // Un ítem que se saca nunca se facturó (el turno no lo está): se borra, la auditoría guarda qué era.
      await tx.gym_turno_items.delete({ where: { id: item_id } });
      await this.recalcularCabecera(tx, t.id);
    });
    const t = await this.turno(item.turno_id, empresa_id);
    await this.auditar(
      empresa_id,
      user_id,
      'EDITAR',
      item.turno_id,
      `Turno de ${t.cliente.nombre}: se sacó un servicio`,
      item,
      undefined,
    );
    return t;
  }

  async cancelar(id: string, motivo: string, empresa_id: string, user_id?: string) {
    const a = await this.prisma.gym_turnos.findFirst({ where: { id, empresa_id }, select: { estado: true } });
    if (!a) throw new NotFoundException('No se encontró el turno');
    if (a.estado !== E.RESERVADO && a.estado !== E.LLEGO)
      throw new BadRequestException('Solo se cancela un turno que todavía no empezó');
    await this.prisma.gym_turnos.update({
      where: { id },
      data: {
        estado: E.CANCELADO,
        motivo_cancelacion: motivo.trim(),
        cancelado_at: new Date(),
        cancelado_por: user_id ?? null,
        updated_at: new Date(),
      },
    });
    const t = await this.turno(id, empresa_id);
    await this.auditar(
      empresa_id,
      user_id,
      'EDITAR',
      id,
      `Turno cancelado de ${t.cliente.nombre}: ${motivo.trim()}`,
      { estado: a.estado },
      { estado: E.CANCELADO, motivo },
    );
    return t;
  }

  /** Llegó, en curso, realizado, no vino (o un paso atrás si se marcó por error). */
  async marcar(id: string, estado: E, empresa_id: string, user_id?: string) {
    const a = await this.prisma.gym_turnos.findFirst({ where: { id, empresa_id }, include: INCLUDE_TURNO });
    if (!a) throw new NotFoundException('No se encontró el turno');
    const error = errorTransicion(a.estado, estado, a.cortesia);
    if (error) throw new BadRequestException(error);
    if (estado !== E.RESERVADO && Date.now() < a.inicio.getTime() - MARCAR_ANTES_MS)
      throw new BadRequestException('Todavía falta para el turno: se marca desde 90 minutos antes');
    if (estado === E.REALIZADO) {
      // Sin profesional no hay a quién pagarle (plan §6.1.4 punto 4).
      const sinProfesional = a.items.filter(
        (i) => !i.profesional_id && (i.servicio.requiere_profesional || i.servicio.paga_profesional),
      );
      if (sinProfesional.length)
        throw new BadRequestException(
          `Elegí la profesional de ${sinProfesional.map((i) => i.servicio.nombre).join(', ')} antes de marcarlo realizado`,
        );
    }
    await this.prisma.gym_turnos.update({
      where: { id },
      data: {
        estado,
        ...(estado === E.LLEGO && !a.llego_at && { llego_at: new Date() }),
        ...(estado === E.RESERVADO && { llego_at: null }),
        realizado_at: estado === E.REALIZADO ? new Date() : null,
        updated_at: new Date(),
      },
    });
    const t = await this.turno(id, empresa_id);
    await this.auditar(
      empresa_id,
      user_id,
      'EDITAR',
      id,
      `Turno de ${t.cliente.nombre}: ${a.estado} → ${estado}`,
      { estado: a.estado },
      { estado },
    );
    return t;
  }

  /** Cortesía: un turno realizado que no se cobra, con motivo (plan §6.1.5 punto 6). */
  async cortesia(id: string, motivo: string, empresa_id: string, user_id?: string) {
    const a = await this.prisma.gym_turnos.findFirst({
      where: { id, empresa_id },
      select: { estado: true, cortesia: true },
    });
    if (!a) throw new NotFoundException('No se encontró el turno');
    if (a.estado !== E.REALIZADO)
      throw new BadRequestException('La cortesía se marca sobre un turno realizado y sin facturar');
    if (a.cortesia) throw new BadRequestException('El turno ya es una cortesía');
    await this.prisma.gym_turnos.update({
      where: { id },
      data: { cortesia: true, motivo_cortesia: motivo.trim(), updated_at: new Date() },
    });
    const t = await this.turno(id, empresa_id);
    await this.auditar(
      empresa_id,
      user_id,
      'EDITAR',
      id,
      `Turno de ${t.cliente.nombre}: cortesía (${motivo.trim()})`,
      { cortesia: false },
      { cortesia: true, motivo },
    );
    return t;
  }

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

  private async turnoEditable(tx: Tx, id: string, empresa_id: string) {
    const t = await tx.gym_turnos.findFirst({
      where: { id, empresa_id },
      select: {
        id: true,
        estado: true,
        dia: true,
        sede: { select: { id: true, nombre: true } },
        items: { orderBy: { orden: 'asc' }, select: { id: true, orden: true, fin: true } },
      },
    });
    if (!t) throw new NotFoundException('No se encontró el turno');
    if (t.estado !== E.RESERVADO && t.estado !== E.LLEGO)
      throw new BadRequestException('Solo se cambian los servicios de un turno que todavía no empezó');
    return t;
  }

  /** Un día a la vez por empresa: lo que se verifica no lo ocupa otra recepción hasta el commit. */
  private async bloquearDia(tx: Tx, empresa_id: string, dia: string) {
    await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`gym_turnos_${empresa_id}_${dia}`}))`;
  }

  /**
   * Valida los ítems y decide recurso y horario (encadenados: sin hora, empiezan cuando termina el anterior). Debe
   * correr con el día bloqueado. `excluir` son ítems que se están reemplazando (no se chocan consigo mismos).
   */
  private async ubicar(
    tx: Tx,
    empresa_id: string,
    sede: { id: string; nombre: string },
    dia: string,
    items: ItemTurnoDto[],
    excluir: string[],
    ordenInicial: number,
  ) {
    const cfg = await tx.gym_config.upsert({ where: { empresa_id }, create: { empresa_id }, update: {} });
    const horario = horarioDelDia(cfg.horario_spa, diaSemanaIso(dia));
    const servicios = await tx.gym_servicios.findMany({
      where: { empresa_id, activo: true, id: { in: [...new Set(items.map((i) => i.servicio_id))] } },
      select: {
        id: true,
        nombre: true,
        modalidad: true,
        duracion_min: true,
        unidad_tiempo_min: true,
        fraccion_minima: true,
        sala_ids: true,
      },
    });
    const recursos = await tx.gym_salas.findMany({
      where: { empresa_id, sede_id: sede.id, activo: true, tipo: { in: RECURSOS_SPA } },
      select: { id: true, nombre: true, capacidad: true },
    });
    const ocupados = await tx.gym_turno_items.findMany({
      where: {
        empresa_id,
        turno: { dia: aFecha(dia), estado: { in: TURNOS_QUE_OCUPAN } },
        ...(excluir.length && { id: { notIn: excluir } }),
      },
      select: { id: true, sala_id: true, profesional_id: true, inicio: true, fin: true },
    });

    const filas: Array<{
      orden: number;
      servicio_id: string;
      sala_id: string | null;
      profesional_id: string | null;
      inicio: Date;
      fin: Date;
      cantidad: number;
    }> = [];
    let anterior: Date | null = null;
    for (const [n, it] of items.entries()) {
      const servicio = servicios.find((s) => s.id === it.servicio_id);
      if (!servicio) throw new BadRequestException('El servicio no existe o está dado de baja');
      if (servicio.modalidad !== gym_servicio_modalidad.TURNO)
        throw new BadRequestException(`${servicio.nombre} no se agenda por turno (es de otra modalidad)`);
      const errCant = errorCantidad(it.cantidad, Number(servicio.fraccion_minima), servicio.nombre);
      if (errCant) throw new BadRequestException(errCant);
      const hora = it.hora ?? (anterior ? horaPy(anterior) : null);
      if (!hora) throw new BadRequestException('Elegí la hora del servicio');
      const duracion = duracionDe(it.cantidad, unidadDe(servicio));
      const horaFin = finDe(hora, duracion);
      if (!horaFin) throw new BadRequestException(`${servicio.nombre} terminaría al día siguiente`);
      const errHorario = errorHorario(hora, horaFin, horario);
      if (errHorario) throw new BadRequestException(errHorario);
      const inicio = instanteDe(dia, hora);
      const fin = new Date(inicio.getTime() + duracion * 60_000);
      const intervalo = { inicio, fin };
      const todos = [...ocupados, ...filas.map((f, k) => ({ id: `nuevo-${k}`, ...f }))];

      // Profesional: de la empresa, con el servicio y la sede, y sin otro turno a la vez.
      let profesional_id: string | null = null;
      if (it.profesional_id) {
        const p = await tx.gym_staff.findFirst({
          where: { id: it.profesional_id, empresa_id, activo: true },
          select: { id: true, nombre: true, servicio_ids: true, sede_ids: true },
        });
        if (!p) throw new BadRequestException('La profesional no existe o está dada de baja');
        if (p.servicio_ids.length && !p.servicio_ids.includes(servicio.id))
          throw new BadRequestException(
            `${p.nombre} no tiene asignado ${servicio.nombre} (Instructores y profesionales)`,
          );
        if (p.sede_ids.length && !p.sede_ids.includes(sede.id))
          throw new BadRequestException(`${p.nombre} no atiende en ${sede.nombre}`);
        const choque = choqueDeRecurso(
          intervalo,
          todos.filter((o) => o.profesional_id === p.id),
          1,
        );
        if (choque)
          throw new ConflictException(
            `${p.nombre} ya tiene un turno de ${horaPy(choque.inicio)} a ${horaPy(choque.fin)}`,
          );
        profesional_id = p.id;
      }

      // Recurso: el pedido (de los del servicio, si el servicio los tiene) o el primero libre de los del servicio.
      const posibles = it.sala_id ? [it.sala_id] : servicio.sala_ids;
      if (it.sala_id && servicio.sala_ids.length && !servicio.sala_ids.includes(it.sala_id))
        throw new BadRequestException(`${servicio.nombre} no se hace en ese recurso (ver Planes y servicios)`);
      const candidatos = posibles
        .map((id) => recursos.find((r) => r.id === id))
        .filter((r): r is (typeof recursos)[number] => !!r);
      if (it.sala_id && !candidatos.length)
        throw new BadRequestException('El recurso no existe en esa sede o está dado de baja');
      if (!it.sala_id && servicio.sala_ids.length && !candidatos.length)
        throw new BadRequestException(`${servicio.nombre} no tiene recursos activos en ${sede.nombre}`);
      let sala_id: string | null = null;
      for (const r of candidatos) {
        if (
          !choqueDeRecurso(
            intervalo,
            todos.filter((o) => o.sala_id === r.id),
            r.capacidad ?? 1,
          )
        ) {
          sala_id = r.id;
          break;
        }
      }
      if (candidatos.length && !sala_id)
        throw new ConflictException(
          it.sala_id
            ? `${candidatos[0].nombre} está ocupada de ${hora} a ${horaFin}`
            : `No hay ${servicio.nombre.toLowerCase()} libre de ${hora} a ${horaFin}`,
        );

      filas.push({
        orden: ordenInicial + n,
        servicio_id: servicio.id,
        sala_id,
        profesional_id,
        inicio,
        fin,
        cantidad: it.cantidad,
      });
      anterior = fin;
    }
    return filas;
  }

  /** La cabecera cubre del primer ítem al último. */
  private async recalcularCabecera(tx: Tx, turno_id: string) {
    const r = await tx.gym_turno_items.aggregate({ where: { turno_id }, _min: { inicio: true }, _max: { fin: true } });
    if (r._min.inicio && r._max.fin)
      await tx.gym_turnos.update({
        where: { id: turno_id },
        data: { inicio: r._min.inicio, fin: r._max.fin, updated_at: new Date() },
      });
  }

  /** Precios de lista de un cliente (o sin cliente: `-`). Un precio que no se pudo leer viaja como `error`, no como 0. */
  private async cargarPrecios(
    empresa_id: string,
    precios: Precios,
    cliente_id: string | null,
    productoIds: string[],
    base: string | null,
  ) {
    const faltan = [...new Set(productoIds)].filter((p) => !precios.has(`${cliente_id ?? '-'}|${p}`));
    if (!faltan.length) return;
    try {
      const r = await this.listaPrecios.obtenerPreciosProductosBatch({
        productoIds: faltan,
        empresaId: empresa_id,
        clienteId: cliente_id ?? undefined,
      });
      for (const p of faltan) {
        const x = r[p];
        precios.set(
          `${cliente_id ?? '-'}|${p}`,
          x
            ? { monto: Number(x.precioFinal ?? 0), moneda: x.moneda ?? base, error: null }
            : { monto: 0, moneda: base, error: 'El producto del servicio no tiene precio' },
        );
      }
    } catch (err) {
      for (const p of faltan)
        precios.set(`${cliente_id ?? '-'}|${p}`, {
          monto: 0,
          moneda: base,
          error: `No se pudo leer el precio: ${(err as Error)?.message ?? err}`,
        });
    }
  }

  private async planoConPrecios(empresa_id: string, t: TurnoConRelaciones) {
    const base = (await monedaBaseOpcional(this.prisma, empresa_id))?.codigo ?? null;
    const precios: Precios = new Map();
    await this.cargarPrecios(
      empresa_id,
      precios,
      t.cliente_id,
      t.items.map((i) => i.servicio.producto_id),
      base,
    );
    return this.plano(t, precios, base);
  }

  private plano(t: TurnoConRelaciones, precios: Precios, base: string | null) {
    const p = t.cliente.personas;
    const items = t.items.map((i) => {
      const precio = precios.get(`${t.cliente_id}|${i.servicio.producto_id}`);
      const cantidad = Number(i.cantidad);
      const real = num(i.cantidad_real);
      const moneda = precio?.moneda ?? base;
      const importe =
        precio && !precio.error
          ? new Prisma.Decimal(precio.monto)
              .mul(real ?? cantidad)
              .toDecimalPlaces(decimalesDe(moneda))
              .toNumber()
          : null;
      return {
        id: i.id,
        orden: i.orden,
        servicio: {
          id: i.servicio.id,
          nombre: i.servicio.nombre,
          producto_id: i.servicio.producto_id,
          unidad_min: unidadDe(i.servicio),
          requiere_profesional: i.servicio.requiere_profesional,
          paga_profesional: i.servicio.paga_profesional,
        },
        sala: i.sala,
        profesional: i.profesional,
        hora_inicio: horaPy(i.inicio),
        hora_fin: horaPy(i.fin),
        duracion_min: Math.round((i.fin.getTime() - i.inicio.getTime()) / 60_000),
        cantidad,
        cantidad_real: real,
        precio_unitario: precio && !precio.error ? precio.monto : null,
        importe_estimado: importe,
        precio_error: precio?.error ?? null,
        moneda,
        facturado: !!i.factura_det_id,
        importe_facturado: i.factura_det ? Number(i.factura_det.dtotopeitem) : null,
      };
    });
    return {
      id: t.id,
      estado: t.estado,
      dia: deFecha(t.dia),
      hora_inicio: horaPy(t.inicio),
      hora_fin: horaPy(t.fin),
      canal: t.canal,
      telefono_contacto: t.telefono_contacto,
      notas: t.notas,
      motivo_cancelacion: t.motivo_cancelacion,
      cortesia: t.cortesia,
      motivo_cortesia: t.motivo_cortesia,
      factura: t.factura
        ? { id: t.factura.id, numero: `${t.factura.dest}-${t.factura.dpunexp}-${t.factura.dnumdoc}` }
        : null,
      sede: t.sede,
      socio: t.socio,
      cliente: {
        id: t.cliente.id,
        nombre: p?.razon_social ?? '',
        documento: documentoDe(p),
        telefono: t.telefono_contacto || p?.celular || p?.telefono || null,
      },
      items,
    };
  }

  /** Totales del día por recurso (el pie del cuaderno): realizados, facturados y la diferencia, por moneda. */
  private totales(planos: ReturnType<TurnosGymService['plano']>[], recursos: Array<{ id: string; nombre: string }>) {
    const filas = recursos.map((r) => {
      const items = planos.flatMap((t) => t.items.filter((i) => i.sala?.id === r.id).map((i) => ({ t, i })));
      const realizados = items.filter(({ t }) => t.estado === E.REALIZADO || t.estado === E.FACTURADO);
      return {
        sala_id: r.id,
        nombre: r.nombre,
        turnos: items.length,
        realizados: realizados.length,
        // Lo realizado se estima con la lista; lo facturado sale de la factura. Una cortesía no suma a cobrar.
        realizado_importe: realizados.reduce((s, { i }) => s + (i.importe_estimado ?? 0), 0),
        facturado_importe: realizados.reduce((s, { i }) => s + (i.importe_facturado ?? 0), 0),
        sin_facturar: realizados.filter(({ t, i }) => !i.facturado && !t.cortesia).length,
      };
    });
    return filas;
  }

  private async auditar(
    empresa_id: string,
    user_id: string | undefined,
    action: 'CREAR' | 'EDITAR',
    id: string,
    descripcion: string,
    old_value?: object,
    new_value?: object,
  ) {
    await this.audit.log({
      empresa_id,
      user_id,
      action,
      entity_type: 'gym_turnos',
      entity_id: id,
      descripcion: descripcion.slice(0, 255),
      old_value: old_value as Record<string, unknown> | undefined,
      new_value: new_value as Record<string, unknown> | undefined,
    });
  }

  /** La sede pedida o, si la empresa tiene una sola activa, esa. En la agenda, sin sedes devuelve null. */
  private async sede(db: Tx | PrismaService, empresa_id: string, sede_id: string | undefined, opcional: boolean) {
    if (sede_id) {
      const s = await db.gym_sedes.findFirst({
        where: { id: sede_id, empresa_id, activo: true },
        select: { id: true, nombre: true },
      });
      if (!s) throw new BadRequestException('La sede no existe o está dada de baja');
      return s;
    }
    const sedes = await db.gym_sedes.findMany({
      where: { empresa_id, activo: true },
      select: { id: true, nombre: true },
      orderBy: { created_at: 'asc' },
    });
    if (sedes.length === 1 || (opcional && sedes.length)) return sedes[0];
    if (opcional) return null;
    throw new BadRequestException(
      sedes.length ? 'Elegí la sede' : 'Primero cargá una sede en Configuración del gimnasio',
    );
  }
}

/** Se exporta para que la recepción pregunte si un cliente tiene el spa del día (sauna y piscina habilitados). */
export const ESTADOS_CON_ACCESO_DEL_DIA: E[] = [E.LLEGO, E.EN_CURSO, E.REALIZADO, E.FACTURADO];
