import { HandlerContext } from "$fresh/server.ts";
import { setCookie } from "http/cookie.ts";
import { Status } from "http/http_status.ts";
import { connectDB } from "../../src/user/db.ts";
import { getUser, verifyUser } from "../../src/user/user.ts";
import { create as createJWT } from "djwt";
import { prepareSecretKey } from "../../util/secret.ts";


const SECRET_KEY = await prepareSecretKey(); 

async function POST(req: Request, ctx: HandlerContext): Promise<Response> {
    const url = new URL(req.url);
    const form = await req.formData();
    const username = form.get("username");
    const password = form.get("password");
    if (username && password){
        const DB = connectDB();
        const user = await getUser(DB, username.toString());
        if (user){
            if (await verifyUser(user, password.toString())){
                const headers = new Headers();
                const jwt = await createJWT({alg:"HS512", typ: "JWT"},{
                    username: user.name
                }, SECRET_KEY);
                setCookie(headers, {
                    name: "auth",
                    value: jwt,
                    httpOnly: true,
                    sameSite: "Strict",
                    maxAge: 60 * 60 * 24 * 7,
                    domain: url.hostname,
                    path: "/",
                    secure: url.protocol === "https:"
                });

                headers.set("Location", "/");
                return new Response(null,{
                    status: Status.SeeOther, // See Other
                    headers: headers
                });
            }
        }
    }

    return new Response(`<!DOCTYPE html><html>
<head> <title> Login Failed </title> </head>
<body>
    <h1> Login Failed </h1>
    <p> <a href="/"> Back to Home </a> </p>
    <script>
        document.location.href = "/login";
    </script>
</body>
</html>`, {
        headers:{
            "Content-Type": "text/html"
        },
        status: Status.Forbidden,
    });
}

export const handler = {
    POST
};