import { BadRequestException, Injectable, InternalServerErrorException, Logger } from '@nestjs/common';
import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { randomUUID } from 'crypto';
import sharp from 'sharp';
import { envs } from 'src/config';

export type ArchivoSocio = 'foto' | 'firma';

const MAX_BYTES = 5 * 1024 * 1024;
const URL_SEG = 600;

/**
 * Foto y firma del socio en Spaces con ACL privada (como los legajos de RRHH):
 * se guardan por clave y se muestran con URL firmada de corta duración.
 * Ruta: gimnasio/{empresa_id}/{socio_id}/{foto|firma}-{uuid}.{webp|png}
 */
@Injectable()
export class ArchivosGymService {
  private readonly logger = new Logger(ArchivosGymService.name);
  private readonly client = new S3Client({
    endpoint: envs.doSpacesEndpoint,
    region: envs.doSpacesRegion,
    credentials: { accessKeyId: envs.doSpacesKey, secretAccessKey: envs.doSpacesSecret },
  });

  /** `data:image/...;base64,...` (la cámara web y el lienzo de la firma) → buffer. */
  private decodificar(dataUrl: string): Buffer {
    const m = /^data:image\/(png|jpe?g|webp);base64,([A-Za-z0-9+/=\s]+)$/.exec(dataUrl ?? '');
    if (!m) throw new BadRequestException('La imagen no es válida (PNG, JPG o WEBP)');
    const buffer = Buffer.from(m[2], 'base64');
    if (buffer.length > MAX_BYTES) throw new BadRequestException('La imagen pesa más de 5 MB');
    return buffer;
  }

  async subir(empresaId: string, socioId: string, tipo: ArchivoSocio, dataUrl: string): Promise<string> {
    const origen = this.decodificar(dataUrl);
    let cuerpo: Buffer;
    try {
      cuerpo =
        tipo === 'foto'
          ? await sharp(origen).rotate().resize({ width: 600, height: 600, fit: 'cover' }).webp({ quality: 80 }).toBuffer()
          : await sharp(origen).resize({ width: 900, withoutEnlargement: true }).png().toBuffer();
    } catch {
      throw new BadRequestException('No se pudo leer la imagen');
    }
    const key = `gimnasio/${empresaId}/${socioId}/${tipo}-${randomUUID()}.${tipo === 'foto' ? 'webp' : 'png'}`;
    try {
      await this.client.send(
        new PutObjectCommand({
          Bucket: envs.doSpacesBucket,
          Key: key,
          Body: cuerpo,
          ContentType: tipo === 'foto' ? 'image/webp' : 'image/png',
          ACL: 'private',
          Metadata: { empresa_id: empresaId, socio_id: socioId },
        }),
      );
    } catch (err) {
      this.logger.error(`No se pudo subir ${key}: ${(err as Error)?.message}`);
      throw new InternalServerErrorException(`No se pudo guardar la ${tipo === 'foto' ? 'foto' : 'firma'}. Probá de nuevo.`);
    }
    return key;
  }

  /**
   * URL firmada para mostrar la imagen. Sin clave: `{ url: null, error: null }` (no hay foto). Si la firma falla, la
   * pantalla recibe el motivo en `error` y lo muestra («No se pudo cargar la foto»): antes llegaba `null` y parecía que
   * el socio no tenía foto.
   */
  async imagen(key: string | null | undefined): Promise<{ url: string | null; error: string | null }> {
    if (!key) return { url: null, error: null };
    try {
      const url = await getSignedUrl(this.client, new GetObjectCommand({ Bucket: envs.doSpacesBucket, Key: key }), { expiresIn: URL_SEG });
      return { url, error: null };
    } catch (err) {
      this.logger.warn(`No se pudo firmar la URL de ${key}: ${(err as Error)?.message}`);
      return { url: null, error: 'No se pudo cargar la imagen desde el almacenamiento. Recargá en unos minutos.' };
    }
  }
}
