---
import Layout from '../layouts/Layout.astro';
import NavBar from '../components/NavBar.astro';

import { getUserByNickOrEmail, updateLastLogin } from '../lib/db/users';

import config from '../../config.json';

import { verify } from 'argon2';
import locationManager from '../lib/classes/managers/LocationManager';

let error = "";

if(Astro.request.method === "POST") {
    const data = await Astro.request.formData();
    const username = data.get("username") as string | "";
    const password = data.get("password") as string | "";

    if(username === "") error = "username is required";
    if(password === "") error = "password is required";

    if(error === "") {
        const userDB = await getUserByNickOrEmail(username as string);

        if(userDB !== null && await verify(userDB.password, password as string)) {
            const user = locationManager.getUser(userDB._id);
            if(!user) throw new Error("User not found");
            const sessionTime = config.SESSION_TIME_MINUTES * 60;

            const res = await fetch(`${Astro.url.origin}/api/auth/generateAccessToken`, {
                method: 'POST',
                body: JSON.stringify({
                    username,
                    createdFrom: 'loginForm',
                    duration: sessionTime
                }),
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + config.MASTER_ACCESSTOKEN
                }
            });
            
            const token = (await res.json()).accessToken;

            await updateLastLogin(user);

            Astro.cookies.set("sessionToken", token, {
                path: "/",
                maxAge: sessionTime,
                sameSite: "lax",
                secure: true
            });

            Astro.cookies.set("username", username, {
                path: "/",
                maxAge: sessionTime,
                sameSite: "lax",
                secure: true
            });

            Astro.cookies.set("userid", user.id?.toString() as string, {
                path: "/",
                maxAge: sessionTime,
                sameSite: "lax",
                secure: true
            });

            Astro.cookies.set("currentPlanet", user.mainPlanet._id, {
                path: "/",
                maxAge: sessionTime,
                sameSite: "lax",
                secure: true
            });

            return Astro.redirect("/game");
        } else error = "invalid username or password";
    }
}
---

<Layout title="Login">
    <NavBar loggedIn="false" active="login" />
    <form method="POST" class="login-form">
        <input class="login-input" type="text" name="username" placeholder="username" /><br />
        <input class="login-input" type="password" name="password" placeholder="password" /><br />
        <input class="login-submit" type="submit" value="login" />
        <p style="color: red;">{error}</p>
    </form>
</Layout>
<style>
.login-form {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 50px;
    background: linear-gradient(
        to bottom right,
        red,
        blue
    );
    padding: 30px;
    text-align: center;
    width: 300px;
    margin-left: auto;
    margin-right: auto;
    border-radius: 10px;
}

.login-input {
    margin: 5px;
    border-radius: 5px;
    border: 1px solid #ccc;
    width: 100%;
    padding: 10px;
}

.login-submit {
    margin: 5px;
    border-radius: 5px;
    border: 1px solid #ccc;
    width: 100%;
    padding: 10px;
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
}
</style>