import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { gym_alcance_sedes, gym_plan_tipo, 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 { exigirIds, idsUnicos, lanzarSiHayErrores } from '../common/gym-utils';
import { ProductoGymService } from '../common/producto-gym.service';
import { erroresPlan } from '../common/reglas';
import { CreatePlanGymDto, UpdatePlanGymDto } from './dto/catalogo.dto';

const INCLUDE_PRODUCTO = {
  producto: { select: { id: true, descripcion: true, cod_producto: true, precio: true } },
  matricula_producto: { select: { id: true, descripcion: true, precio: true } },
} satisfies Prisma.gym_planesInclude;

/** Campos del plan que dependen del tipo: los que no aplican se guardan vacíos. */
function normalizarPorTipo(p: {
  tipo: gym_plan_tipo;
  alcance_sedes: gym_alcance_sedes;
  sedes_permitidas: string[];
  creditos: number | null;
  creditos_actividades: string[];
  vencimiento_creditos_dias: number | null;
  congelamientos_max: number;
  congelamiento_dias_min: number | null;
  congelamiento_dias_max: number | null;
}) {
  const usaCreditos = p.tipo === gym_plan_tipo.CREDITOS || p.tipo === gym_plan_tipo.MIXTO;
  return {
    sedes_permitidas: p.alcance_sedes === gym_alcance_sedes.LISTA ? p.sedes_permitidas : [],
    creditos: usaCreditos ? p.creditos : null,
    creditos_actividades: usaCreditos ? p.creditos_actividades : [],
    vencimiento_creditos_dias: usaCreditos ? p.vencimiento_creditos_dias : null,
    congelamiento_dias_min: p.congelamientos_max > 0 ? p.congelamiento_dias_min : null,
    congelamiento_dias_max: p.congelamientos_max > 0 ? p.congelamiento_dias_max : null,
  };
}

/**
 * Planes de membresía (mensual, pase, paquete de clases…).
 * El plan se vende en el POS como su producto; el precio es el del producto o su
 * lista de precios. Baja lógica.
 */
@Injectable()
export class PlanesGymService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
    private readonly productoGym: ProductoGymService,
  ) {}

  /** El precio es el del producto, en la moneda base de la empresa: cada plan la trae para rotularlo. */
  async listar(empresa_id: string, incluir_inactivos = false) {
    const [planes, moneda] = await Promise.all([
      this.prisma.gym_planes.findMany({
        where: { empresa_id, ...(incluir_inactivos ? {} : { activo: true }) },
        include: INCLUDE_PRODUCTO,
        orderBy: [{ activo: 'desc' }, { nombre: 'asc' }],
      }),
      monedaBaseOpcional(this.prisma, empresa_id),
    ]);
    return planes.map((p) => ({ ...p, moneda }));
  }

  async detalle(id: string, empresa_id: string) {
    const plan = await this.prisma.gym_planes.findFirst({ where: { id, empresa_id }, include: INCLUDE_PRODUCTO });
    if (!plan) throw new NotFoundException('Plan no encontrado');
    return plan;
  }

  /** Sedes y actividades elegidas existen, están activas y son de la empresa. */
  private async validarReferencias(
    empresa_id: string,
    p: { sedes_permitidas: string[]; actividades_incluidas: string[]; creditos_actividades: string[]; matricula_producto_id: string | null },
  ) {
    await exigirIds(
      p.sedes_permitidas,
      (ids) => this.prisma.gym_sedes.findMany({ where: { empresa_id, activo: true, id: { in: ids } }, select: { id: true } }),
      'Alguna de las sedes elegidas no existe o está dada de baja',
    );
    await exigirIds(
      idsUnicos([...p.actividades_incluidas, ...p.creditos_actividades]),
      (ids) =>
        this.prisma.gym_actividades.findMany({ where: { empresa_id, activo: true, id: { in: ids } }, select: { id: true } }),
      'Alguna de las actividades elegidas no existe o está dada de baja',
    );
    if (p.matricula_producto_id) {
      await this.productoGym.validarExistente(p.matricula_producto_id, empresa_id, 'El producto de la matrícula');
    }
  }

  private async validarNombre(empresa_id: string, nombre: string, excepto?: string) {
    const otro = await this.prisma.gym_planes.findFirst({
      where: {
        empresa_id,
        activo: true,
        nombre: { equals: nombre, mode: 'insensitive' },
        ...(excepto && { id: { not: excepto } }),
      },
      select: { id: true },
    });
    if (otro) throw new ConflictException(`Ya existe el plan "${nombre}"`);
  }

  async crear(dto: CreatePlanGymDto, empresa_id: string, user_id?: string) {
    const nombre = dto.nombre.trim();
    const base = {
      tipo: dto.tipo,
      duracion_valor: dto.duracion_valor ?? null,
      duracion_unidad: dto.duracion_unidad ?? null,
      alcance_sedes: dto.alcance_sedes ?? gym_alcance_sedes.SEDE_BASE,
      sedes_permitidas: idsUnicos(dto.sedes_permitidas),
      hora_desde: dto.hora_desde ?? null,
      hora_hasta: dto.hora_hasta ?? null,
      actividades_incluidas: idsUnicos(dto.actividades_incluidas),
      creditos: dto.creditos ?? null,
      creditos_actividades: idsUnicos(dto.creditos_actividades),
      vencimiento_creditos_dias: dto.vencimiento_creditos_dias ?? null,
      invitados_mes: dto.invitados_mes ?? 0,
      pases_visita_mes: dto.pases_visita_mes ?? 0,
      congelamientos_max: dto.congelamientos_max ?? 0,
      congelamiento_dias_min: dto.congelamiento_dias_min ?? null,
      congelamiento_dias_max: dto.congelamiento_dias_max ?? null,
      requiere_matricula: dto.requiere_matricula ?? false,
      matricula_producto_id: dto.requiere_matricula ? (dto.matricula_producto_id ?? null) : null,
      admite_menores: dto.admite_menores ?? true,
      renovable: dto.renovable ?? true,
    };
    lanzarSiHayErrores(erroresPlan(base));
    await this.validarNombre(empresa_id, nombre);
    await this.validarReferencias(empresa_id, base);

    // Todo validado antes de tocar productos: así un plan inválido no deja un producto suelto.
    let producto_id = dto.producto_id;
    if (producto_id) {
      await this.productoGym.validarExistente(producto_id, empresa_id);
      await this.productoGym.validarLibre(producto_id, empresa_id);
    } else {
      if (dto.precio == null) throw new BadRequestException('Indicá el precio del plan (o elegí un producto existente)');
      producto_id = await this.productoGym.crear(nombre, dto.precio, empresa_id, user_id);
    }

    const plan = await this.prisma.gym_planes.create({
      data: { empresa_id, producto_id, nombre, ...base, ...normalizarPorTipo(base), created_by: user_id ?? null },
      include: INCLUDE_PRODUCTO,
    });
    await this.audit.log({ empresa_id, user_id, action: 'CREAR', entity_type: 'gym_plan', entity_id: plan.id, new_value: plan });
    return plan;
  }

  /**
   * F0: todavía no hay membresías, así que todo es editable. Desde F1, cambiar el
   * tipo o la duración de un plan con membresías vigentes no debe alterarlas.
   */
  async actualizar(id: string, dto: UpdatePlanGymDto, empresa_id: string, user_id?: string) {
    const anterior = await this.detalle(id, empresa_id);
    if (!anterior.activo) throw new ConflictException('El plan está dado de baja');
    const nombre = dto.nombre?.trim();
    if (nombre && nombre.toLowerCase() !== anterior.nombre.toLowerCase()) await this.validarNombre(empresa_id, nombre, id);

    const requiere_matricula = dto.requiere_matricula ?? anterior.requiere_matricula;
    const merged = {
      tipo: dto.tipo ?? anterior.tipo,
      duracion_valor: dto.duracion_valor !== undefined ? dto.duracion_valor : anterior.duracion_valor,
      duracion_unidad: dto.duracion_unidad !== undefined ? dto.duracion_unidad : anterior.duracion_unidad,
      alcance_sedes: dto.alcance_sedes ?? anterior.alcance_sedes,
      sedes_permitidas: dto.sedes_permitidas ? idsUnicos(dto.sedes_permitidas) : anterior.sedes_permitidas,
      hora_desde: dto.hora_desde !== undefined ? dto.hora_desde : anterior.hora_desde,
      hora_hasta: dto.hora_hasta !== undefined ? dto.hora_hasta : anterior.hora_hasta,
      actividades_incluidas: dto.actividades_incluidas ? idsUnicos(dto.actividades_incluidas) : anterior.actividades_incluidas,
      creditos: dto.creditos !== undefined ? dto.creditos : anterior.creditos,
      creditos_actividades: dto.creditos_actividades ? idsUnicos(dto.creditos_actividades) : anterior.creditos_actividades,
      vencimiento_creditos_dias:
        dto.vencimiento_creditos_dias !== undefined ? dto.vencimiento_creditos_dias : anterior.vencimiento_creditos_dias,
      invitados_mes: dto.invitados_mes ?? anterior.invitados_mes,
      pases_visita_mes: dto.pases_visita_mes ?? anterior.pases_visita_mes,
      congelamientos_max: dto.congelamientos_max ?? anterior.congelamientos_max,
      congelamiento_dias_min:
        dto.congelamiento_dias_min !== undefined ? dto.congelamiento_dias_min : anterior.congelamiento_dias_min,
      congelamiento_dias_max:
        dto.congelamiento_dias_max !== undefined ? dto.congelamiento_dias_max : anterior.congelamiento_dias_max,
      requiere_matricula,
      matricula_producto_id: requiere_matricula
        ? dto.matricula_producto_id !== undefined
          ? dto.matricula_producto_id
          : anterior.matricula_producto_id
        : null,
      admite_menores: dto.admite_menores ?? anterior.admite_menores,
      renovable: dto.renovable ?? anterior.renovable,
    };
    lanzarSiHayErrores(erroresPlan(merged));
    await this.validarReferencias(empresa_id, merged);

    if (dto.precio != null && Number(dto.precio) !== Number(anterior.producto.precio ?? 0)) {
      await this.productoGym.actualizarPrecio(anterior.producto_id, dto.precio, empresa_id, user_id);
    }
    // El producto lleva el nombre del plan mientras nadie lo haya renombrado aparte.
    if (nombre && nombre !== anterior.nombre && anterior.producto.descripcion === anterior.nombre) {
      await this.productoGym.renombrar(anterior.producto_id, nombre, empresa_id, user_id);
    }

    const plan = await this.prisma.gym_planes.update({
      where: { id },
      data: { ...(nombre && { nombre }), ...merged, ...normalizarPorTipo(merged), updated_at: new Date() },
      include: INCLUDE_PRODUCTO,
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'gym_plan',
      entity_id: id,
      old_value: anterior,
      new_value: plan,
    });
    return plan;
  }

  /** El producto queda como está: puede tener ventas. Darlo de baja es una decisión aparte. */
  async darDeBaja(id: string, empresa_id: string, user_id?: string) {
    const plan = await this.detalle(id, empresa_id);
    if (!plan.activo) return plan;
    const baja = await this.prisma.gym_planes.update({
      where: { id },
      data: { activo: false, updated_at: new Date() },
      include: INCLUDE_PRODUCTO,
    });
    await this.audit.log({ empresa_id, user_id, action: 'ELIMINAR', entity_type: 'gym_plan', entity_id: id, old_value: plan });
    return baja;
  }

  /**
   * Vuelve a ofrecer un plan dado de baja. Lo que elige (sedes, actividades, matrícula) tiene que
   * seguir activo y el nombre no puede chocar con otro plan activo.
   */
  async reactivar(id: string, empresa_id: string, user_id?: string) {
    const plan = await this.detalle(id, empresa_id);
    if (plan.activo) return plan;
    await this.validarNombre(empresa_id, plan.nombre, id);
    await this.validarReferencias(empresa_id, plan);
    const alta = await this.prisma.gym_planes.update({
      where: { id },
      data: { activo: true, updated_at: new Date() },
      include: INCLUDE_PRODUCTO,
    });
    await this.audit.log({ empresa_id, user_id, action: 'REACTIVAR', entity_type: 'gym_plan', entity_id: id, old_value: plan, new_value: alta });
    return alta;
  }
}
