const express = require('express');
const path = require('path');
const schemas = require('../models/schemas');
const statusCodes = require('../helpers/status_codes');

const config = require('../config/credentials.json');

const router = express.Router();

router.get('/', (req, res) => {
    res.sendFile('login.html', {root: path.join(__dirname, '..', 'public', 'html')});
});

function validateLogin(req, res, next) {
    const {error, value} = schemas.loginModelSchema.validate(req.body);

    if (error) {
        res.status(statusCodes.BAD_REQUEST).json({error: error.details});
    } else {
        next();
    }
}

router.post('/', validateLogin, (req, res) => {
    const { email, password } = req.body;

    if (email === config.email && password === config.password) {
        res.status(statusCodes.OK).json({
            success: true,
            message: 'Login successful',
            user: {
                id: config.id,
                name: config.name,
                email: config.email
            }
        });
    } else {
        res.status(statusCodes.UNAUTHORIZED).json({message: 'Invalid email or password' });
    }
});
module.exports = router;
