"use server";

import { cookies } from "next/headers";
import { APIError, UserAuth, parseBasicAuth, getAssociatedUser } from "@/util";
import { Auth, User } from "@/models";

async function tryAuth(request: Request) {
	// await User.sync();
	await Auth.sync();

	const auth: string | null = request.headers.get("authorization");

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

	const userAuth = parseBasicAuth(auth);
	const user = await getAssociatedUser(userAuth);

	if (!user || !user.id) return new Response("error", { status: 500 });

	const authentication = await Auth.create({
		user_id: user.id,
	});

	console.log("ok");
	const foundAuth = await Auth.findOne({
		include: {
			model: User,
			as: "user",
		},
		where: {
			user_id: user.id,
		},
	});
	console.log("ok2");

	if (!foundAuth) return new Response("error", { status: 500 });

	const usr = foundAuth.user;

	const authUser = await authentication.getUser();

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

	return new Response(
		JSON.stringify({
			credentials: userAuth,
			auth: authentication,
			user: authUser,
			foundAuth: foundAuth,
		}),
		{
			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;
		}
	}
}
