import { BadRequestException } from '@nestjs/common';

/**
 * Capturas que adjunta el cliente (plan §6.10). El panel ya las achica (lado mayor 1568 px,
 * lo que el modelo aprovecha); acá solo se valida que sean de verdad PNG, JPEG o WebP y
 * que no pesen de más. Nada se interpreta ni se reescala en el servidor.
 */
export const TIPOS_IMAGEN = ['image/png', 'image/jpeg', 'image/webp'] as const;
export type TipoImagen = (typeof TIPOS_IMAGEN)[number];

export const MAX_IMAGENES = 3;
export const MAX_BYTES_IMAGEN = 3 * 1024 * 1024;

export interface Imagen {
  tipo: TipoImagen;
  datos: Buffer;
}

/** La firma de los primeros bytes tiene que coincidir con el tipo declarado. */
function firmaValida(tipo: TipoImagen, b: Buffer): boolean {
  if (tipo === 'image/png')
    return b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
  if (tipo === 'image/jpeg') return b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff;
  return b.subarray(0, 4).toString('latin1') === 'RIFF' && b.subarray(8, 12).toString('latin1') === 'WEBP';
}

export function leerImagenes(entrada: Array<{ tipo: string; datos: string }> = []): Imagen[] {
  if (entrada.length > MAX_IMAGENES) throw new BadRequestException(`Podés adjuntar hasta ${MAX_IMAGENES} imágenes.`);
  return entrada.map((x, i) => {
    const tipo = x.tipo as TipoImagen;
    if (!TIPOS_IMAGEN.includes(tipo)) throw new BadRequestException(`La imagen ${i + 1} no es PNG, JPEG ni WebP.`);
    const datos = Buffer.from(x.datos, 'base64');
    if (!datos.length || datos.length > MAX_BYTES_IMAGEN) {
      throw new BadRequestException(`La imagen ${i + 1} pesa más de ${MAX_BYTES_IMAGEN / 1024 / 1024} MB.`);
    }
    if (!firmaValida(tipo, datos)) throw new BadRequestException(`La imagen ${i + 1} no es una imagen válida.`);
    return { tipo, datos };
  });
}
