import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { gym_membresia_estado, gym_plan_tipo, gym_socio_estado, gym_socio_origen, Prisma } from '@prisma/client';
import { AuditService } from 'src/audit/audit.service';
import { PrismaService } from 'src/prisma/prisma.service';
import { situacionDeAcceso } from '../common/acceso-reglas';
import { aFecha, deFecha, diaPy, edadEn, sumarDias } from '../common/fechas-gym';
import { textoONull } from '../common/gym-utils';
import { documentoDe, siguienteNumeroSocio } from '../common/socio-utils';
import { ESTADOS_MEMBRESIA_FUERA } from '../ventas/gym-ventas.service';
import { ArchivosGymService } from './archivos-gym.service';
import { CambiarEstadoSocioDto, CreateSocioGymDto, UpdateSocioGymDto } from './dto/socio.dto';

const PERSONA = { select: { razon_social: true, nro_documento: true, ruc: true, dv: true, email: true, celular: true, telefono: true } };
const MEMBRESIA_PLAN = { select: { id: true, nombre: true, tipo: true, producto_id: true } };

type MembresiaConPlan = Prisma.gym_membresiasGetPayload<{ include: { plan: typeof MEMBRESIA_PLAN } }>;

/** Membresía con fechas como 'YYYY-MM-DD' (lo que entienden las reglas y la pantalla). */
export function membresiaPlana<T extends { fecha_inicio: Date; fecha_fin: Date; fecha_fin_original: Date; ultimo_credito_fecha?: Date | null }>(m: T) {
  return {
    ...m,
    fecha_inicio: deFecha(m.fecha_inicio),
    fecha_fin: deFecha(m.fecha_fin),
    fecha_fin_original: deFecha(m.fecha_fin_original),
    ultimo_credito_fecha: m.ultimo_credito_fecha ? deFecha(m.ultimo_credito_fecha) : null,
  };
}

/**
 * Socios: un cliente del ERP + lo propio del gimnasio. El alta valida la edad
 * mínima y guarda foto y firma en el almacenamiento privado. Nunca se borra:
 * se suspende o se da de baja con motivo.
 */
@Injectable()
export class SociosGymService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
    private readonly archivos: ArchivosGymService,
  ) {}

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

  private async deEmpresa(id: string, empresa_id: string) {
    const s = await this.prisma.gym_socios.findFirst({ where: { id, empresa_id } });
    if (!s) throw new NotFoundException('No se encontró el socio');
    return s;
  }

  /** Edad mínima, menores y tutor según la configuración (regla 9). */
  private async validarEdad(empresa_id: string, fecha_nacimiento: string, tutor_cliente_id: string | null) {
    const hoy = diaPy();
    if (fecha_nacimiento > hoy) throw new BadRequestException('La fecha de nacimiento no puede ser futura');
    const edad = edadEn(fecha_nacimiento, hoy);
    if (edad > 110) throw new BadRequestException('Revisá la fecha de nacimiento');
    const cfg = await this.config(empresa_id);
    if (cfg.edad_minima != null && edad < cfg.edad_minima) {
      throw new BadRequestException(`La edad mínima para ser socio es ${cfg.edad_minima} años (tiene ${edad})`);
    }
    if (edad < 18 && !cfg.admite_menores) throw new BadRequestException('El gimnasio no admite menores de 18 años');
    if (edad < 18 && cfg.menor_requiere_tutor && !tutor_cliente_id) {
      throw new BadRequestException('Para un menor de 18 años hay que cargar quién firma por él (tutor)');
    }
    return cfg;
  }

  private async validarReferencias(
    empresa_id: string,
    r: { sede_base_id?: string | null; tutor_cliente_id?: string | null; referido_por_socio_id?: string | null },
    socioId?: string,
  ) {
    if (r.sede_base_id) {
      const sede = await this.prisma.gym_sedes.findFirst({ where: { id: r.sede_base_id, empresa_id, activo: true }, select: { id: true } });
      if (!sede) throw new BadRequestException('La sede no existe o está dada de baja');
    }
    if (r.tutor_cliente_id) await this.clienteDeEmpresa(r.tutor_cliente_id, empresa_id, 'El tutor no es un cliente de la empresa');
    if (r.referido_por_socio_id) {
      if (r.referido_por_socio_id === socioId) throw new BadRequestException('Un socio no puede referirse a sí mismo');
      const ref = await this.prisma.gym_socios.findFirst({ where: { id: r.referido_por_socio_id, empresa_id }, select: { id: true } });
      if (!ref) throw new BadRequestException('El socio que lo refirió no existe');
    }
  }

  private async clienteDeEmpresa(cliente_id: string, empresa_id: string, mensaje = 'El cliente no existe en esta empresa') {
    const c = await this.prisma.clientes.findFirst({
      where: { id: cliente_id, deleted: false, personas: { empresa_id } },
      select: { id: true, personas: PERSONA },
    });
    if (!c) throw new BadRequestException(mensaje);
    return c;
  }

  /** La primera sede activa, si la empresa tiene una sola (el selector está oculto). */
  private async sedeUnica(empresa_id: string): Promise<string | null> {
    const sedes = await this.prisma.gym_sedes.findMany({ where: { empresa_id, activo: true }, select: { id: true }, take: 2 });
    return sedes.length === 1 ? sedes[0].id : null;
  }

  async crear(dto: CreateSocioGymDto, empresa_id: string, user_id?: string) {
    const cliente = await this.clienteDeEmpresa(dto.cliente_id, empresa_id);
    const cfg = await this.validarEdad(empresa_id, dto.fecha_nacimiento, dto.tutor_cliente_id ?? null);
    await this.validarReferencias(empresa_id, dto);
    if (cfg.reglamento?.trim() && !dto.acepta_reglamento) {
      throw new BadRequestException('El socio tiene que aceptar el reglamento');
    }

    const existente = await this.prisma.gym_socios.findUnique({
      where: { empresa_id_cliente_id: { empresa_id, cliente_id: dto.cliente_id } },
    });
    // Le vendieron el plan antes del alta: el alta completa esa ficha en vez de duplicarla.
    if (existente && !existente.ficha_incompleta) {
      throw new ConflictException(`${cliente.personas?.razon_social ?? 'El cliente'} ya es el socio N° ${existente.numero_socio}`);
    }

    const datos = {
      fecha_nacimiento: aFecha(dto.fecha_nacimiento),
      telefono: textoONull(dto.telefono) ?? textoONull(cliente.personas?.celular) ?? textoONull(cliente.personas?.telefono),
      email: textoONull(dto.email) ?? textoONull(cliente.personas?.email),
      sede_base_id: dto.sede_base_id ?? existente?.sede_base_id ?? (await this.sedeUnica(empresa_id)),
      contacto_emergencia_nombre: textoONull(dto.contacto_emergencia_nombre),
      contacto_emergencia_telefono: textoONull(dto.contacto_emergencia_telefono),
      tutor_cliente_id: dto.tutor_cliente_id ?? null,
      acepta_avisos_email: dto.acepta_avisos_email ?? true,
      referido_por_socio_id: dto.referido_por_socio_id ?? null,
      observaciones: textoONull(dto.observaciones),
      reglamento_firmado_at: dto.acepta_reglamento ? new Date() : null,
      apto_fisico_vence: dto.apto_fisico_vence ? aFecha(dto.apto_fisico_vence) : (existente?.apto_fisico_vence ?? null),
      ficha_incompleta: false,
    };

    let socio = existente
      ? await this.prisma.gym_socios.update({ where: { id: existente.id }, data: { ...datos, updated_at: new Date() } })
      : await this.prisma.$transaction(async (tx) =>
          tx.gym_socios.create({
            data: {
              empresa_id,
              cliente_id: dto.cliente_id,
              numero_socio: await siguienteNumeroSocio(tx, empresa_id),
              origen: datos.referido_por_socio_id ? gym_socio_origen.REFERIDO : gym_socio_origen.WALK_IN,
              ...datos,
              created_by: user_id ?? null,
            },
          }),
        );
    socio = await this.guardarImagenes(socio.id, empresa_id, dto);
    await this.audit.log({
      empresa_id,
      user_id,
      action: existente ? 'EDITAR' : 'CREAR',
      entity_type: 'gym_socios',
      entity_id: socio.id,
      descripcion: existente
        ? `Alta del socio N° ${socio.numero_socio}: se completó la ficha creada en la venta`
        : `Alta del socio N° ${socio.numero_socio}`,
      new_value: this.paraAuditoria(socio),
    });
    return this.detalle(socio.id, empresa_id);
  }

  private async guardarImagenes(id: string, empresa_id: string, dto: { foto?: string; firma?: string }) {
    const data: Prisma.gym_sociosUpdateInput = {};
    if (dto.foto) data.foto_key = await this.archivos.subir(empresa_id, id, 'foto', dto.foto);
    if (dto.firma) data.firma_key = await this.archivos.subir(empresa_id, id, 'firma', dto.firma);
    if (!Object.keys(data).length) return this.prisma.gym_socios.findFirstOrThrow({ where: { id, empresa_id } });
    return this.prisma.gym_socios.update({ where: { id }, data: { ...data, updated_at: new Date() } });
  }

  private paraAuditoria(s: { foto_key?: string | null; firma_key?: string | null } & Record<string, unknown>) {
    const { foto_key, firma_key, ...resto } = s;
    return { ...resto, tiene_foto: !!foto_key, tiene_firma: !!firma_key };
  }

  async actualizar(id: string, dto: UpdateSocioGymDto, empresa_id: string, user_id?: string) {
    const anterior = await this.deEmpresa(id, empresa_id);
    if (dto.fecha_nacimiento !== undefined) {
      await this.validarEdad(empresa_id, dto.fecha_nacimiento, dto.tutor_cliente_id !== undefined ? dto.tutor_cliente_id : anterior.tutor_cliente_id);
    }
    await this.validarReferencias(empresa_id, dto, id);
    const data: Prisma.gym_sociosUncheckedUpdateInput = { updated_at: new Date() };
    if (dto.fecha_nacimiento !== undefined) data.fecha_nacimiento = aFecha(dto.fecha_nacimiento);
    if (dto.telefono !== undefined) data.telefono = textoONull(dto.telefono);
    if (dto.email !== undefined) data.email = textoONull(dto.email);
    if (dto.sede_base_id !== undefined) data.sede_base_id = dto.sede_base_id;
    if (dto.contacto_emergencia_nombre !== undefined) data.contacto_emergencia_nombre = textoONull(dto.contacto_emergencia_nombre);
    if (dto.contacto_emergencia_telefono !== undefined) data.contacto_emergencia_telefono = textoONull(dto.contacto_emergencia_telefono);
    if (dto.tutor_cliente_id !== undefined) data.tutor_cliente_id = dto.tutor_cliente_id;
    if (dto.acepta_avisos_email !== undefined) data.acepta_avisos_email = dto.acepta_avisos_email;
    if (dto.referido_por_socio_id !== undefined) data.referido_por_socio_id = dto.referido_por_socio_id;
    if (dto.observaciones !== undefined) data.observaciones = textoONull(dto.observaciones);
    if (dto.apto_fisico_vence !== undefined) data.apto_fisico_vence = dto.apto_fisico_vence ? aFecha(dto.apto_fisico_vence) : null;
    if (dto.acepta_reglamento && !anterior.reglamento_firmado_at) data.reglamento_firmado_at = new Date();
    if (data.fecha_nacimiento || anterior.fecha_nacimiento) data.ficha_incompleta = false;
    await this.prisma.gym_socios.update({ where: { id }, data });
    const socio = await this.guardarImagenes(id, empresa_id, dto);
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'gym_socios',
      entity_id: id,
      old_value: this.paraAuditoria(anterior),
      new_value: this.paraAuditoria(socio),
    });
    return this.detalle(id, empresa_id);
  }

  /** Activar, suspender o dar de baja (con motivo). La baja no anula membresías pagadas. */
  async cambiarEstado(id: string, dto: CambiarEstadoSocioDto, empresa_id: string, user_id?: string) {
    const anterior = await this.deEmpresa(id, empresa_id);
    const motivo = textoONull(dto.motivo);
    if (dto.estado !== gym_socio_estado.ACTIVO && !motivo) throw new BadRequestException('Indicá el motivo');
    if (anterior.estado === dto.estado) return this.detalle(id, empresa_id);
    await this.prisma.gym_socios.update({
      where: { id },
      data: { estado: dto.estado, motivo_estado: dto.estado === gym_socio_estado.ACTIVO ? null : motivo, updated_at: new Date() },
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: dto.estado === gym_socio_estado.BAJA ? 'ELIMINAR' : 'EDITAR',
      entity_type: 'gym_socios',
      entity_id: id,
      descripcion: `Socio N° ${anterior.numero_socio}: ${anterior.estado} → ${dto.estado}${motivo ? ` (${motivo})` : ''}`,
      old_value: { estado: anterior.estado },
      new_value: { estado: dto.estado, motivo },
    });
    return this.detalle(id, empresa_id);
  }

  /**
   * Listado con la situación de la membresía de acceso. Busca por número de
   * socio, nombre, CI o RUC.
   */
  async listar(
    empresa_id: string,
    f: { q?: string; estado?: gym_socio_estado; situacion?: string; page?: number; limit?: number } = {},
  ) {
    const page = Math.max(1, f.page ?? 1);
    const limit = Math.min(100, Math.max(1, f.limit ?? 25));
    const hoy = diaPy();
    // La situación se filtra en la base con la misma regla que `situacionDeAcceso` (antes se traían 2000 y se paginaba
    // en memoria: con más socios el total quedaba corto sin aviso, relevamiento B-11).
    const where: Prisma.gym_sociosWhereInput = {
      AND: [this.whereBusqueda(empresa_id, f.q, f.estado), whereSituacion(f.situacion, hoy)],
      empresa_id,
    };
    const [total, socios] = await Promise.all([
      this.prisma.gym_socios.count({ where: { ...where, empresa_id } }),
      this.prisma.gym_socios.findMany({
        where: { ...where, empresa_id },
        include: { cliente: { select: { personas: PERSONA } }, sede_base: { select: { id: true, nombre: true } } },
        orderBy: { numero_socio: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
    ]);
    const membresias = socios.length
      ? await this.prisma.gym_membresias.findMany({
          where: { empresa_id, socio_id: { in: socios.map((s) => s.id) }, estado: { notIn: ESTADOS_MEMBRESIA_FUERA } },
          include: { plan: MEMBRESIA_PLAN },
        })
      : [];
    const porSocio = new Map<string, ReturnType<typeof membresiaPlana<MembresiaConPlan>>[]>();
    for (const m of membresias) {
      const lista = porSocio.get(m.socio_id) ?? [];
      lista.push(membresiaPlana(m));
      porSocio.set(m.socio_id, lista);
    }
    const filas = socios.map((s) => {
      const sit = situacionDeAcceso(porSocio.get(s.id) ?? [], hoy);
      return {
        id: s.id,
        numero_socio: s.numero_socio,
        nombre: s.cliente.personas?.razon_social ?? '',
        documento: documentoDe(s.cliente.personas),
        telefono: s.telefono,
        email: s.email,
        estado: s.estado,
        ficha_incompleta: s.ficha_incompleta,
        sede_base: s.sede_base,
        situacion: sit.situacion,
        dias: sit.dias,
        plan: sit.membresia?.plan.nombre ?? null,
        fecha_fin: sit.membresia?.fecha_fin ?? null,
      };
    });
    return { data: filas, total, page, limit };
  }

  whereBusqueda(empresa_id: string, q?: string, estado?: gym_socio_estado): Prisma.gym_sociosWhereInput {
    const t = q?.trim();
    const numero = t && /^\d{1,9}$/.test(t) ? Number(t) : null;
    return {
      empresa_id,
      ...(estado && { estado }),
      ...(t && {
        OR: [
          ...(numero != null ? [{ numero_socio: numero }] : []),
          { cliente: { personas: { razon_social: { contains: t, mode: 'insensitive' as const } } } },
          { cliente: { personas: { nro_documento: { startsWith: t } } } },
          { cliente: { personas: { ruc: { startsWith: t } } } },
        ],
      }),
    };
  }

  /** Ficha del socio: datos, membresías, últimos ingresos y avisos. */
  async detalle(id: string, empresa_id: string) {
    const s = await this.prisma.gym_socios.findFirst({
      where: { id, empresa_id },
      include: {
        cliente: { select: { id: true, personas: PERSONA } },
        tutor: { select: { id: true, personas: PERSONA } },
        sede_base: { select: { id: true, nombre: true } },
        referido_por: { select: { id: true, numero_socio: true, cliente: { select: { personas: { select: { razon_social: true } } } } } },
      },
    });
    if (!s) throw new NotFoundException('No se encontró el socio');
    const [membresias, accesos, avisos, foto, firma] = await Promise.all([
      this.prisma.gym_membresias.findMany({
        where: { empresa_id, socio_id: id },
        include: {
          plan: MEMBRESIA_PLAN,
          factura: { select: { id: true, dest: true, dpunexp: true, dnumdoc: true, dfeemide: true, moneda: { select: { codigo: true } } } },
          sede_venta: { select: { id: true, nombre: true } },
        },
        orderBy: [{ fecha_inicio: 'desc' }, { created_at: 'desc' }],
      }),
      this.prisma.gym_accesos.findMany({
        where: { empresa_id, socio_id: id },
        include: { sede: { select: { nombre: true } }, membresia: { select: { plan: { select: { nombre: true } } } } },
        orderBy: { fecha_hora: 'desc' },
        take: 30,
      }),
      this.prisma.gym_avisos_log.findMany({
        where: { empresa_id, socio_id: id },
        include: { membresia: { select: { plan: { select: { nombre: true } }, fecha_fin: true } } },
        orderBy: { created_at: 'desc' },
        take: 30,
      }),
      this.archivos.imagen(s.foto_key),
      this.archivos.imagen(s.firma_key),
    ]);
    const hoy = diaPy();
    // Las cargadas sin factura muestran quién lo hizo (plan ya pagado, §15.12).
    const cargadores = [...new Set(membresias.filter((m) => !m.factura_id && m.created_by).map((m) => m.created_by!))];
    const usuarios = cargadores.length
      ? await this.prisma.usuario.findMany({ where: { id: { in: cargadores } }, select: { id: true, nombres: true, apellidos: true, username: true } })
      : [];
    const nombreUsuario = new Map(usuarios.map((u) => [u.id, [u.nombres, u.apellidos].filter(Boolean).join(' ') || u.username || '']));
    const planas = membresias.map((m) => ({
      ...membresiaPlana(m),
      numero_factura: m.factura ? `${m.factura.dest}-${m.factura.dpunexp}-${m.factura.dnumdoc}` : null,
      cargada_por: !m.factura_id && m.created_by ? (nombreUsuario.get(m.created_by) ?? null) : null,
    }));
    const sit = situacionDeAcceso(
      planas.filter((m) => !ESTADOS_MEMBRESIA_FUERA.includes(m.estado as (typeof ESTADOS_MEMBRESIA_FUERA)[number])),
      hoy,
    );
    // Las claves del almacenamiento privado no salen: la pantalla usa las URL firmadas.
    const resto = { ...s, foto_key: undefined, firma_key: undefined, apto_fisico_key: undefined };
    return {
      ...resto,
      fecha_nacimiento: s.fecha_nacimiento ? deFecha(s.fecha_nacimiento) : null,
      apto_fisico_vence: s.apto_fisico_vence ? deFecha(s.apto_fisico_vence) : null,
      edad: s.fecha_nacimiento ? edadEn(deFecha(s.fecha_nacimiento), hoy) : null,
      nombre: s.cliente.personas?.razon_social ?? '',
      documento: documentoDe(s.cliente.personas),
      foto_url: foto.url,
      foto_error: foto.error,
      firma_url: firma.url,
      firma_error: firma.error,
      situacion: sit.situacion,
      dias: sit.dias,
      membresia_actual_id: sit.membresia?.id ?? null,
      membresias: planas,
      accesos,
      avisos: avisos.map((a) => ({ ...a, membresia: a.membresia ? { ...a.membresia, fecha_fin: deFecha(a.membresia.fecha_fin) } : null })),
    };
  }

  /**
   * Anulación manual (devolución del dinero, error de carga). La factura no se
   * toca: si corresponde, la nota de crédito se hace aparte.
   */
  async anularMembresia(id: string, motivo: string, empresa_id: string, user_id?: string) {
    const m = await this.prisma.gym_membresias.findFirst({ where: { id, empresa_id }, include: { plan: { select: { nombre: true } } } });
    if (!m) throw new NotFoundException('No se encontró la membresía');
    if (m.estado === gym_membresia_estado.ANULADA) throw new ConflictException('La membresía ya está anulada');
    const texto = motivo.trim().slice(0, 500);
    await this.prisma.gym_membresias.update({
      where: { id },
      data: { estado: gym_membresia_estado.ANULADA, motivo_anulacion: texto, anulada_at: new Date(), anulada_por: user_id ?? null, updated_at: new Date() },
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'EDITAR',
      entity_type: 'gym_membresias',
      entity_id: id,
      descripcion: `Membresía ${m.plan.nombre} anulada a mano: ${texto}`,
      old_value: { estado: m.estado },
      new_value: { estado: gym_membresia_estado.ANULADA, motivo: texto },
    });
    return this.detalle(m.socio_id, empresa_id);
  }
}

/**
 * La situación de `situacionDeAcceso` como filtro de Prisma (sin los días): vigente si alguna membresía de acceso cubre
 * hoy; futura si no y alguna empieza después; vencida si no y alguna terminó; sin plan si no tiene ninguna. Los paquetes
 * de créditos y las anuladas/reemplazadas no cuentan. Una situación desconocida no filtra.
 */
export function whereSituacion(situacion: string | undefined, hoy: string): Prisma.gym_sociosWhereInput {
  const dia = aFecha(hoy);
  const acceso: Prisma.gym_membresiasWhereInput = {
    estado: { notIn: ESTADOS_MEMBRESIA_FUERA },
    plan: { tipo: { not: gym_plan_tipo.CREDITOS } },
  };
  const vigente = { gym_membresias: { some: { ...acceso, fecha_inicio: { lte: dia }, fecha_fin: { gte: dia } } } };
  const futura = { gym_membresias: { some: { ...acceso, fecha_inicio: { gt: dia } } } };
  const vencida = { gym_membresias: { some: { ...acceso, fecha_fin: { lt: dia } } } };
  switch (situacion) {
    case 'VIGENTE':
      return vigente;
    case 'FUTURA':
      return { AND: [{ NOT: vigente }, futura] };
    case 'VENCIDA':
      return { AND: [{ NOT: vigente }, { NOT: futura }, vencida] };
    case 'SIN_PLAN':
      return { gym_membresias: { none: acceso } };
    case 'POR_VENCER': {
      // Vigentes que vencen en los próximos 7 días sin una renovación que los cubra después (como `situacionDeAcceso`:
      // VIGENTE con dias ≤ 7). Lo usa el KPI «Vencen en 7 días» del Inicio (relevamiento A#18). Los pases no cuentan:
      // nacen por vencer (como el tablero).
      const en7 = aFecha(sumarDias(hoy, 7));
      const en8 = aFecha(sumarDias(hoy, 8));
      const sinPases = { ...acceso, plan: { tipo: { notIn: [gym_plan_tipo.CREDITOS, gym_plan_tipo.PASE] } } };
      return {
        AND: [
          { gym_membresias: { some: { ...sinPases, fecha_inicio: { lte: dia }, fecha_fin: { gte: dia, lte: en7 } } } },
          { NOT: { gym_membresias: { some: { ...acceso, fecha_inicio: { lte: en8 }, fecha_fin: { gt: en7 } } } } },
        ],
      };
    }
    default:
      return {};
  }
}
