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

/**
 * Archivos del vertical en DigitalOcean Spaces (mismo bucket que el resto del ERP),
 * privados y servidos con URL firmada. Ruta: `inmobiliario/{empresa}/{carpeta}/{año}/{id}.{ext}`.
 * Mismo patrón que `rrhh/services/legajos-storage.service.ts`, con ruta propia.
 */
@Injectable()
export class InmStorageService {
  private readonly logger = new Logger(InmStorageService.name);
  private readonly client = new S3Client({
    endpoint: envs.doSpacesEndpoint,
    region: envs.doSpacesRegion,
    credentials: { accessKeyId: envs.doSpacesKey, secretAccessKey: envs.doSpacesSecret },
  });

  clave(empresa_id: string, carpeta: string, id: string, nombreArchivo: string) {
    const ext =
      (nombreArchivo.split('.').pop() ?? 'bin')
        .toLowerCase()
        .replace(/[^a-z0-9]/g, '')
        .slice(0, 8) || 'bin';
    return `inmobiliario/${empresa_id}/${carpeta}/${new Date().getUTCFullYear()}/${id}.${ext}`;
  }

  async subir(key: string, buffer: Buffer, mime: string) {
    try {
      await this.client.send(
        new PutObjectCommand({
          Bucket: envs.doSpacesBucket,
          Key: key,
          Body: buffer,
          ContentType: mime,
          ACL: 'private',
        }),
      );
    } catch (e) {
      this.logger.error(`No se pudo subir ${key}: ${(e as Error).message}`);
      throw new InternalServerErrorException('No se pudo guardar el archivo en el almacenamiento');
    }
  }

  urlFirmada(key: string, nombre: string, mime: string) {
    return getSignedUrl(
      this.client,
      new GetObjectCommand({
        Bucket: envs.doSpacesBucket,
        Key: key,
        ResponseContentType: mime,
        ResponseContentDisposition: `inline; filename*=UTF-8''${encodeURIComponent(nombre)}`,
      }),
      { expiresIn: 600 },
    );
  }
}
