'use server'

import { Model } from "@sequelize/core";
import { cookies } from "next/headers";


import { Auth } from "@/models";


import { APIError} from "@/util/api/error"
import { UserAuth, parseBasicAuth, getAssociatedUser } from "@/util/api/user"


async function tryAuth(request:Request){

    // await User.sync();
    await Auth.sync();

    
    const koek = cookies().get('auth');
    if(!koek){
        return new Response("unauthorized",{status:403});
    }
    console.log(koek);
    const auth = JSON.parse(koek.value);


    const authentication = await Auth.findOne( { include: {
        association: Auth.associations.user
    }, where: { token:auth.token } })

    

    if(!authentication)
        return new Response("unauthorized: invalid token",{status:403});
    

    const authUser = await authentication.getUser();

    // @ts-ignore
    cookies().set('auth', JSON.stringify(authentication));

    return new Response(
        JSON.stringify(
        {
            auth: authentication,
        }),
        { 
            status: 200, 
            headers:{
                "Content-Type": "text/JSON" 
            } 
        }
    ); 
}

export async function POST(request:Request){
    try{
        return await tryAuth(request);      
    }
    catch(e){
        if (e instanceof APIError){
            return new Response(e.info.responseText,{status:e.info.status});
        }
        else{
            throw e;
        }
    }
}
