const express = require('express');
const { execSync } = require('child_process');
const crypto = require('crypto');

const newRepo = require('./commande/newRepo');
const newUser = require('./commande/newUser');
const newGroup = require('./commande/newGroup');
const changePassword = require('./commande/changePassword');
const deleteUser = require('./commande/deleteUser');
const setpermrepo = require('./commande/setpermrepo');
const addInGroup = require('./commande/addInGroup');
const deleteUserInGroup = require('./commande/deleteUserInGroup');
const deleteGroup = require('./commande/deleteGroup');
const getRepos = require('./commande/getRepos');
const deleteRepo = require('./commande/deleteRepo');
const getUsers = require('./commande/getUsers');
const getGroups = require('./commande/getGroups');
const getUseringroup = require('./commande/getUseringroup');
const loginapi = require('./commande/loginapi');
const getperm = require('./commande/getPerm');
const delperm = require('./commande/delPerm');
const removepermreRepo = require('./commande/removepermreRepo');

const app = express();
const port = 8445;

let CURRENT_API_KEY = null;

function generateToken() {
    return crypto.randomBytes(48).toString('hex');
}

function rotateApiKey() {
    CURRENT_API_KEY = generateToken();
    console.log("Nouveau token :", CURRENT_API_KEY);
}

rotateApiKey();

setInterval(rotateApiKey, 24 * 60 * 60 * 1000);

app.use(express.json());

function checkApiKey(req, res, next) {
    const apiKey = req.headers['x-api-key'];
    if (!apiKey || apiKey !== CURRENT_API_KEY) {
        return res.status(403).send("INVALID API KEY");
    }
    next();
}

newRepo(app, checkApiKey);
newUser(app, checkApiKey);
newGroup(app, checkApiKey);
changePassword(app, checkApiKey);
deleteUser(app, checkApiKey);
setpermrepo(app, checkApiKey);
addInGroup(app, checkApiKey);
deleteUserInGroup(app, checkApiKey);
deleteGroup(app, checkApiKey);
getRepos(app, checkApiKey);
deleteRepo(app, checkApiKey);
getUsers(app, checkApiKey);
removepermreRepo(app, checkApiKey);
getGroups(app, checkApiKey);
getUseringroup(app, checkApiKey);
delperm(app, checkApiKey);
getperm(app, checkApiKey);

loginapi(app, () => CURRENT_API_KEY);

app.listen(port, () => {
    console.log(`API HTTP disponible sur http://localhost:${port}`);
});