import { BadRequestException, ForbiddenException, GoneException, Injectable, NotFoundException } from '@nestjs/common';
import { createHash, randomBytes } from 'crypto';
import { AuditService } from 'src/audit/audit.service';
import { envs } from 'src/config/envs';
import { PrismaService } from 'src/prisma/prisma.service';
import { SuscripcionesService } from 'src/suscripciones/suscripciones.service';
import { submoduloPublicoHabilitado } from '../common/submodulo-publico';
import { AccesosGymService } from './accesos-gym.service';
import { CrearTabletDto, IngresoTabletDto } from './dto/tablet.dto';

/** Tope del logo que se reenvía a la tablet. */
const MAX_LOGO_BYTES = 3 * 1024 * 1024;
const hash = (k: string) => createHash('sha256').update(k).digest('hex');

/**
 * Tablet de ingreso sin sesión: se vincula una vez desde Recepción (link con un
 * código propio que la tablet guarda) y queda atada a una sede. La base guarda
 * sólo el hash del código; desvincularla la deja sin acceso al instante. Valida
 * con las mismas reglas y el mismo registro que recepción (`AccesosGymService`).
 */
@Injectable()
export class TabletsGymService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService,
    private readonly accesos: AccesosGymService,
    private readonly suscripciones: SuscripcionesService,
  ) {}

  async listar(empresa_id: string) {
    const filas = await this.prisma.gym_tablets.findMany({
      where: { empresa_id, activo: true },
      include: { sede: { select: { id: true, nombre: true } } },
      orderBy: { created_at: 'asc' },
    });
    return filas.map((t) => ({
      id: t.id,
      nombre: t.nombre,
      sede: t.sede,
      ultimo_uso_at: t.ultimo_uso_at,
      created_at: t.created_at,
    }));
  }

  /** El link se muestra una sola vez: la base no puede reconstruirlo. */
  async crear(empresa_id: string, dto: CrearTabletDto, user_id?: string) {
    const sede = await this.sede(empresa_id, dto.sede_id);
    const k = randomBytes(24).toString('base64url');
    const t = await this.prisma.gym_tablets.create({
      data: {
        empresa_id,
        sede_id: sede.id,
        nombre: dto.nombre.trim(),
        token_hash: hash(k),
        created_by: user_id ?? null,
      },
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'CREAR',
      entity_type: 'gym_tablets',
      entity_id: t.id,
      descripcion: `Tablet de ingreso vinculada: ${t.nombre} (${sede.nombre})`.slice(0, 255),
    });
    return {
      id: t.id,
      nombre: t.nombre,
      sede,
      url: `${envs.urlPanelFrontend.replace(/\/$/, '')}/gym/ingreso?k=${k}`,
    };
  }

  async revocar(empresa_id: string, id: string, user_id?: string) {
    const t = await this.prisma.gym_tablets.findFirst({ where: { id, empresa_id, activo: true } });
    if (!t) throw new NotFoundException('La tablet no existe o ya está desvinculada');
    await this.prisma.gym_tablets.update({
      where: { id },
      data: { activo: false, revocado_at: new Date(), revocado_por: user_id ?? null },
    });
    await this.audit.log({
      empresa_id,
      user_id,
      action: 'ELIMINAR',
      entity_type: 'gym_tablets',
      entity_id: id,
      descripcion: `Tablet de ingreso desvinculada: ${t.nombre}`.slice(0, 255),
    });
    return { ok: true };
  }

  private async sede(empresa_id: string, sede_id?: string) {
    const sedes = await this.prisma.gym_sedes.findMany({
      where: { empresa_id, activo: true, ...(sede_id && { id: sede_id }) },
      select: { id: true, nombre: true },
      take: 2,
    });
    if (sede_id && !sedes.length) throw new BadRequestException('La sede no existe o está dada de baja');
    if (sedes.length === 1) return sedes[0];
    throw new BadRequestException(
      sedes.length ? 'Elegí la sede de la tablet' : 'Primero cargá una sede en Configuración del gimnasio',
    );
  }

  /** Tablet del código, con su empresa y sede activas. */
  private async deCodigo(k: string) {
    const t = await this.prisma.gym_tablets.findUnique({
      where: { token_hash: hash(k) },
      include: {
        sede: { select: { id: true, nombre: true, activo: true } },
        empresas: { select: { razon_social: true, nombre_fantasia: true, logo: true } },
      },
    });
    // 410 y no 404: la tablet distingue «no está vinculada» de «no encontramos esa cédula».
    // Sin Recepción contratada la tablet deja de andar igual que una desvinculada (no se revela por qué).
    if (!t?.activo || !t.sede.activo || !(await submoduloPublicoHabilitado(this.prisma, t.empresa_id, 'GYM_RECEPCION')))
      throw new GoneException('Esta tablet no está vinculada: pedile a recepción que la vincule de nuevo');
    return t;
  }

  /** Pública: a qué gimnasio y sede está atada la tablet. Sin ids. */
  async info(k: string) {
    const t = await this.deCodigo(k);
    return {
      gimnasio: t.empresas.nombre_fantasia || t.empresas.razon_social,
      sede: t.sede.nombre,
      tablet: t.nombre,
      /** Si hay logo para pedir a `logo()`; la URL no se da porque lleva el id de la empresa. */
      logo: !!t.empresas.logo,
    };
  }

  /**
   * Pública: el logo de la empresa (Configuración › Empresa) para la cabecera de la tablet. Se baja del
   * bucket y se entrega la imagen, no la URL (regla 10). Sólo https e imágenes de hasta 3 MB.
   */
  async logo(k: string): Promise<{ contenido: Buffer; tipo: string }> {
    const t = await this.deCodigo(k);
    const url = t.empresas.logo;
    if (!url?.startsWith('https://')) throw new NotFoundException('El gimnasio no tiene logo cargado');
    let r: Response;
    try {
      r = await fetch(url, { signal: AbortSignal.timeout(8_000) });
    } catch {
      throw new NotFoundException('No se pudo traer el logo');
    }
    const tipo = r.headers.get('content-type') ?? '';
    if (!r.ok || !tipo.startsWith('image/')) throw new NotFoundException('No se pudo traer el logo');
    const contenido = Buffer.from(await r.arrayBuffer());
    if (contenido.length > MAX_LOGO_BYTES) throw new NotFoundException('El logo es demasiado pesado');
    return { contenido, tipo };
  }

  /**
   * Pública: el socio escribe su CI (o pasa el QR) y entra. Queda registrado como
   * en recepción, con la tablet como dispositivo. La respuesta no lleva ids ni
   * documento (regla 10): nombre, semáforo y lo justo de su plan.
   */
  async ingreso(dto: IngresoTabletDto) {
    const t = await this.deCodigo(dto.k);
    // Sólo frena una suscripción vencida: la holding y las empresas que dependen de
    // otra no tienen suscripción propia («sin_suscripcion») y el panel tampoco las frena.
    const estado = await this.suscripciones.verificarEstadoSuscripcion(t.empresa_id);
    if (estado.bloqueada && estado.razon !== 'sin_suscripcion')
      throw new ForbiddenException('El ingreso por tablet no está disponible. Pasá por recepción.');
    const r = await this.accesos.validar(
      {
        ...(dto.qr ? { qr: dto.qr } : { documento: dto.documento }),
        sede_id: t.sede_id,
        dispositivo: `Tablet: ${t.nombre}`.slice(0, 100),
      },
      t.empresa_id,
    );
    await this.prisma.gym_tablets.update({ where: { id: t.id }, data: { ultimo_uso_at: new Date() } });
    return {
      semaforo: r.semaforo,
      resultado: r.resultado,
      mensaje: r.mensaje,
      // La foto (URL firmada de 10 min) para que recepción vea de lejos quién entra (diseño, D2). Nunca ids ni documentos.
      socio: { nombre: r.socio.nombre, foto_url: r.socio.foto_url ?? null },
      membresia: r.membresia
        ? {
            plan: r.membresia.plan,
            fecha_fin: r.membresia.fecha_fin,
            creditos_totales: r.membresia.creditos_totales,
            creditos_usados: r.membresia.creditos_usados,
          }
        : null,
    };
  }
}
