import { getUserByAccessToken } from "./lib/db/users";
import { getHighestWeightedLanguage, getLocales } from "./lib/utils/langDriver";
import locationManager from "./lib/classes/managers/LocationManager";
import { defineMiddleware } from "astro/middleware";
import { APIContext, MiddlewareNext } from "astro";
import { ObjectId } from "mongodb";

const frontend = async (context: APIContext, next: MiddlewareNext) => {
    const loggedToken = context.cookies.get('sessionToken')?.value ?? null;
    const username = context.cookies.get('username')?.value ?? "";
    if(loggedToken === null || username === "") return context.redirect('/logout');

    const checkUser = await getUserByAccessToken(loggedToken);
    if(checkUser === null || checkUser.username !== username) return context.redirect('/logout');
    const user = locationManager.getUser(checkUser._id);
    if(user === null) return context.redirect('/logout');

    const lang = await getLocales(context.cookies.get('language')?.value ?? await getHighestWeightedLanguage(context.request.headers.get('accept-language')));

    const activeId = context.cookies.get('currentPlanet')?.value ?? "0";
    const active = locationManager.findId(new ObjectId(activeId));

    if(active === null) return context.redirect('/logout');

    context.locals.token = loggedToken;
    context.locals.lang = lang;
    context.locals.user = user;
    context.locals.active = active;

    return next();
}

export const onRequest = defineMiddleware(async (context, next) => {
    return context.url.pathname.startsWith('/game') ? frontend(context, next) : next();
});