
import crypto from "crypto";

import {
    User
} from "../../lib/database/connect.mjs";


function sendAuthForm(response, errors=[]) {
    response.render(`views/htmx/authForm.njk`, {
        errors: errors
    });
}


export const get = async function(request, response) {
    sendAuthForm(response);
    // response.set('HX-Redirect', '/profile').status(200).end();
}

export const post = async function(request, response) {
    if (!request.body.username || !request.body.password) {
        sendAuthForm(response, [{
            title: 'Username and password are required',
            detail: 'Username or Password was not received.'
        }]);
        return;
    }

    if (typeof request.body.username != 'string' || typeof request.body.password != 'string') {
        sendAuthForm(response, [{
            title: 'Invalid input types',
            detail: 'Username and Password must be strings.'
        }]);
        return;
    }

    let username = request.body.username;
    let password = crypto.createHash('sha256').update(request.body.password).digest('hex')

    // let loginResult = await login(username, password)
    let loginUser = await User.findOne({
        where: {
            name: username,
            passsha256: password
        }
    });

    if (loginUser == null) {
        sendAuthForm(response, [{
            title: 'Login failed',
            detail: 'Invalid Username or Password.'
        }]);
        return;
    }

    if (loginUser.disabled == 1) {
        sendAuthForm(response, [{
            title: 'User disabled',
            detail: 'This user account is disabled.'
        }]);
        return;
    }

    request.session.userid = loginUser.id;
    request.session.save();
    
    if (loginUser.otpsecret == '' || loginUser.otpsecret == null) {
        request.setAuthState('authenticated');
        response.set('HX-Redirect', '/profile').status(200).end();
    } else {
        request.setAuthState('totp-verfication');
        response.redirect('/htmx/totpForm'); 
    }
}