import { processImageToWebP } from "./imageCompresionService";
import * as oracleService from "../services/oracleStorageService";

const BUCKET = process.env.BUCKET_NAME!;
if (!BUCKET) throw new Error("Faltan variables de entorno: BUCKET_NAME");

export type ProcessFileResult = {
    objectName: string;
    originalName: string;
    bufferToUpload: Buffer<ArrayBufferLike>;
    mimeType: string;
};

export const processFile = async (file: Express.Multer.File) => {
    let bufferToUpload = file.buffer;
    let mimeType = file.mimetype;
    const originalName = file.originalname;

    // Si es imagen, procesar con sharp (resize + convertir a jpeg)
    if (mimeType.startsWith("image/")) {
        bufferToUpload = await processImageToWebP(bufferToUpload);
        mimeType = "image/webp";
    }

    // Generar objectName único para evitar colisiones
    const timestamp = Date.now();
    // escapamos/normalizamos el originalName ligeramente
    const safeOriginal = originalName.replace(/\s+/g, "_");
    const objectName = `${timestamp}-${safeOriginal}`;

    // Subir a Oracle
    await oracleService.subirArchivo(BUCKET, objectName, bufferToUpload);

    return {
        objectName,
        originalName,
        bufferToUpload,
        mimeType,
    };
};
