const express = require('express');
const {httpStatus} = require("../helpers/httpResponses");
const {schemas} = require("../models/schemaMapper");
const router = express.Router();

function validateBody(req, res, next) {
    let validationSchema = undefined;

    if(req.path === '/' && req.method === 'PATCH'){
        validationSchema = schemas.dirStructureModelSchema
    }

    if(validationSchema !== undefined){
        console.log(req.body);
        const {error} = validationSchema.validate(req.body);
        if(error){
            const errorMessage = error.details.map(detail => detail.message).join(', ');
            return res.status(httpStatus.BAD_REQUEST).json({ message: errorMessage });
        }
    }
    next();
}

router.patch('/', validateBody, (req, res) => {
    const backupSchemesDB = req.app.get('backupSchemesDB');
    const { id, ip, directoryStructure, totalSize } = req.body;

    let backupSchemesJson = backupSchemesDB.readFile();
    backupSchemesJson[id] = {
        ip: ip,
        directoryStructure: directoryStructure,
        totalSize: totalSize
    }

    backupSchemesDB.writeFile(backupSchemesJson);
    return res.status(httpStatus.OK).json({message: 'Backup schema updated'});
});

router.get('/', validateBody, (req, res) => {
    const backupSchemesDB = req.app.get('backupSchemesDB');
    return res.status(httpStatus.OK).json({
       message: 'Backup Schemes fetched.',
       data: backupSchemesDB.readFile()
    });
});

router.get('/:userId', (req, res) => {
    const userId = req.params.userId;
    const backupSchemesDB = req.app.get('backupSchemesDB');
    let backupSchemesJson = backupSchemesDB.readFile();
    const ip = backupSchemesJson[userId].ip;
    if (ip) {
        res.status(httpStatus.OK).json({message: "IP found", data: ip});
    } else {
        res.status(httpStatus.NOT_FOUND).send({message: "IP not found"});
    }
});

router.use((req, res) => {
    return res.status(httpStatus.NOT_FOUND).json({message: "Endpoint not found"});
})

module.exports = router;
