import type { Request, Response } from "express";
import * as oracleService from "../services/oracleStorageService";

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

const streamToBuffer = async (
    stream: ReadableStream<any> | NodeJS.ReadableStream
): Promise<Buffer> => {
    if ("getReader" in stream) {
        // Es un ReadableStream web
        const reader = stream.getReader();
        const chunks: Uint8Array[] = [];
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            chunks.push(value);
        }
        return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));
    } else {
        // Es un NodeJS ReadableStream
        const chunks: Buffer[] = [];
        return new Promise((resolve, reject) => {
            stream.on("data", (chunk) =>
                chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
            );
            stream.on("end", () => resolve(Buffer.concat(chunks)));
            stream.on("error", reject);
        });
    }
};

export const downloadFile = async (req: Request, res: Response) => {
    try {
        const { nombre } = req.params;
        if (!nombre) return res.status(400).json({ error: "Falta parámetro nombre" });

        const obj = await oracleService.descargarArchivo(BUCKET, nombre);
        // obj.value es un ReadableStream web estándar
        const body: Buffer = await streamToBuffer(obj.value);

        res.setHeader("Content-Disposition", `attachment; filename="${nombre}"`);
        res.send(body);
    } catch (err) {
        console.error("Error en downloadArchivo:", err);
        res.status(500).json({ error: "Error al descargar archivo" });
    }
};
