import axios from "axios";
import FormData from "form-data";
import { IFileManager, UploadFileResponse, UploadPostFileParams } from "./Files.Interface";

class UploadFileManager implements IFileManager {
    constructor() {}

    public async uploadPostFile(data: UploadPostFileParams): Promise<UploadFileResponse> {
        try {
            const apiUrl = `${process.env.FILE_SERVER_URL}upload-by-organization`;
            const accessToken = `${data.token}`;

            // Crear el formulario
            const form = new FormData();
            form.append("files", data.file.buffer, {
                filename: data.file.originalname, // necesario para que el servidor sepa el nombre
                contentType: data.file.mimetype, // necesario para que Multer entienda el tipo
            });
            form.append("sessionUser", data.sessionUser);
            form.append("organizationId", data.companyId);

            // Enviar la solicitud
            const response = await axios.post(apiUrl, form, {
                headers: {
                    ...form.getHeaders(),
                    Authorization: `Bearer ${accessToken}`,
                },
            });

            if (response.status !== 200) {
                throw new Error(`Error al subir el archivo: ${response.statusText}`);
            }

            console.log(">>>>Respuesta del servidor de archivos:>>>>", response.data);

            return response.data as UploadFileResponse;
        } catch (error) {
            //aaas
            console.error("Error al enviar el archi:", error);
            throw error;
        }
    }

    public async downloadFile(objectName: string): Promise<Buffer> {
        const imageUrl = `${process.env.FILE_SERVER_URL}download/${objectName}`;
        const response = await axios.get(imageUrl, { responseType: "arraybuffer" });
        return response.data;
    }
}

const UploadFiles = new UploadFileManager();

export default UploadFiles;
