// Collezzione di tutte le api che prendono i dati da minio
//api.mebboat.it/storage

const express = require('express');
const { getBuckets, getBucket, getObject, getObjects, getFileStream } = require('../storage/minio');
const router = express.Router();

/**
 * Restituisce una lista con tutti i bucket del database, 
 * altrimenti restituisce i file del bucket passato come parametro
 * 
 * @param {string} bucket - il bucket 
 */
router.get('/', async (req, res) => {
    const { bucket } = req.query;

    if (bucket == undefined) {
        const buckets = await getBuckets();
        res.status(200).json(buckets);
    } else {
        const returnBucket = await getBucket(bucket);
        res.status(200).json(returnBucket);
    }
})

router.get('/files', async (req, res) => {
    const { bucket, fileID } = req.query;
    
    if (bucket == undefined) {
        res.status(400).json({ error: "No bucket name in the request" });
    } else {
        if (fileID == undefined) {
            const files = await getObjects(bucket);
            res.status(200).json(files);
        } else {
            const file = await getObject(bucket, fileID);
            res.status(200).json(file);
        }
    }
})

router.get('/file', async (req, res) => {
    const { bucket, fileID } = req.query;
    const stream = await getFileStream(bucket, fileID);
    res.setHeader('Content-Type', 'application/octet-stream');
    stream.pipe(res);
})

router.post('/upload', async (req, res) => {
    const { bucket } = req.query;
    const files = await getObjects(bucket);
    res.status(200).json(files);
})

router.get('/download', async (req, res) => {

})

module.exports = router;