import type { Request, Response } from "express";
import DataProfile from "../models/dataprofile";
import { processFile } from "../services/processFile";
import { validateOrganization } from "../services/validateOrganization";
import type { FileUploadParams } from "../models/types";

export const uploadOrganizationFile = async (req: Request, res: Response) => {
    try {
        const data = await validateOrganization(req, res);
        const procesados: FileUploadParams[] = [];

        for (const file of data.files) {
            const result = await processFile(file);
            const { objectName, originalName, bufferToUpload, mimeType } = result;

            await DataProfile.create({
                objectName,
                originalName,
                size: bufferToUpload.length,
                mimeType,
                userId: data.sessionUser,
                organizationId: data.organizationId,
            });

            procesados.push({ originalName, objectName });
        }

        return res.status(200).json({
            message: `${procesados.length} archivos subidos y registrados`,
            files: procesados,
        });
    } catch (err) {
        console.error("Error en uploadArchivos:", err);
        return res.status(500).json({ error: "Error al subir archivos" });
    }
};
