import { Injectable } from '@nestjs/common';
import { gym_staff_tipo } from '@prisma/client';
import { contextoPlanEmpresa, submoduloHabilitado } from 'src/auth/guards/submodulo.guard';
import { PrismaService } from 'src/prisma/prisma.service';
import { monedaBaseOpcional } from 'src/utils/montos-moneda';
import { ConfigGymService } from '../config/config-gym.service';

/**
 * Lo que las pantallas operativas del gimnasio necesitan para sus selectores y reglas, sin pedir los permisos de
 * Configuración ni de Catálogo (relevamiento 2026-11-10, A#1, B D-1, C D1/D5: Recepción, Clases, Turnos y el alta de
 * socio quedaban bloqueadas con un 403 que se mostraba como «no hay sedes»). Solo nombres y reglas, nada sensible: cada
 * bloque viene si su submódulo está contratado; lo que no, llega vacío.
 */
@Injectable()
export class OpcionesGymService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly config: ConfigGymService,
  ) {}

  async opciones(empresa_id: string) {
    const contexto = await contextoPlanEmpresa(this.prisma, empresa_id);
    const tiene = async (codigo: string) =>
      (await submoduloHabilitado(this.prisma, empresa_id, codigo, contexto)).habilitado;
    const [catalogo, staff, clases, turnos] = await Promise.all([
      tiene('GYM_CATALOGO'),
      tiene('GYM_STAFF'),
      tiene('GYM_CLASES'),
      tiene('GYM_TURNOS'),
    ]);

    const [cfg, moneda, sedes, actividades, servicios, personas, planes] = await Promise.all([
      this.config.obtener(empresa_id),
      monedaBaseOpcional(this.prisma, empresa_id),
      this.prisma.gym_sedes.findMany({
        where: { empresa_id, activo: true },
        select: {
          id: true,
          nombre: true,
          horario_apertura: true,
          gym_salas: {
            where: { activo: true },
            select: { id: true, nombre: true, tipo: true, capacidad: true },
            orderBy: { nombre: 'asc' },
          },
        },
        orderBy: { nombre: 'asc' },
      }),
      catalogo
        ? this.prisma.gym_actividades.findMany({
            where: { empresa_id, activo: true },
            select: { id: true, nombre: true, tipo: true, color: true, duracion_min: true },
            orderBy: { nombre: 'asc' },
          })
        : [],
      catalogo
        ? this.prisma.gym_servicios.findMany({
            where: { empresa_id, activo: true },
            select: {
              id: true,
              nombre: true,
              modalidad: true,
              actividad_id: true,
              duracion_min: true,
              unidad_tiempo_min: true,
              requiere_profesional: true,
              sala_ids: true,
              producto_id: true,
            },
            orderBy: { nombre: 'asc' },
          })
        : [],
      staff
        ? this.prisma.gym_staff.findMany({
            where: { empresa_id, activo: true },
            select: { id: true, nombre: true, tipo: true, actividad_ids: true, servicio_ids: true, sede_ids: true },
            orderBy: { nombre: 'asc' },
          })
        : [],
      // Para elegir el plan en el alta y en «Asignar plan ya pagado», sin pedir el permiso de Catálogo.
      this.prisma.gym_planes.findMany({
        where: { empresa_id, activo: true },
        select: { id: true, nombre: true, tipo: true, producto_id: true, creditos: true, producto: { select: { cod_producto: true, descripcion: true } } },
        orderBy: { nombre: 'asc' },
      }),
    ]);

    return {
      moneda,
      submodulos: { catalogo, staff, clases, turnos },
      reglas: {
        usa_multisede: cfg.usa_multisede,
        modo_vencido: cfg.modo_vencido,
        admite_menores: cfg.admite_menores,
        edad_minima: cfg.edad_minima,
        menor_requiere_tutor: cfg.menor_requiere_tutor,
        apto_fisico_modo: cfg.apto_fisico_modo,
        qr_rotacion_seg: cfg.qr_rotacion_seg,
        ventana_reserva_horas: cfg.ventana_reserva_horas,
        horas_cancelacion_sin_penalidad: cfg.horas_cancelacion_sin_penalidad,
        reglamento: cfg.reglamento,
        consentimiento: cfg.consentimiento,
      },
      sedes: sedes.map(({ gym_salas, ...s }) => ({ ...s, salas: gym_salas })),
      actividades,
      servicios,
      instructores: personas.filter((p) => p.tipo === gym_staff_tipo.INSTRUCTOR),
      profesionales: personas.filter((p) => p.tipo === gym_staff_tipo.PROFESIONAL),
      planes,
    };
  }
}
