import type { Handle, HandleServerError } from "@sveltejs/kit";
import { sequence } from "@sveltejs/kit/hooks";
import { auth } from "$lib/domains/auth/config/base";
import { svelteKitHandler } from "better-auth/svelte-kit";
import type { UserModel } from "@pkg/logic/domains/user/data/entities";
import { createTRPCHandle } from "trpc-sveltekit";
import { router } from "$lib/trpc/router";
import { createContext } from "$lib/trpc/context";

export const handleError: HandleServerError = async ({ error, event }) => {
	console.log("[-] Running error middleware for : ", event.url.pathname);
	console.log(error);
	return { message: (error as Error).message ?? "Internal Server Error" };
};

export const zero: Handle = async ({ event, resolve }) => {
	return svelteKitHandler({ event, resolve, auth });
};

export const first: Handle = async ({ event, resolve }) => {
	if (
		event.url.pathname.includes("/api/auth") ||
		event.url.pathname.includes("/api/debug") ||
		event.url.pathname.includes("/api/calling") ||
		event.url.pathname.includes("/auth")
	) {
		return await resolve(event);
	}
	console.log("[+] Running middleware for : ", event.url.pathname);
	const baseUrl = event.url.origin;
	const signInUrl = baseUrl + "/auth/login";
	const isSignInPage = event.url.pathname === "/auth/login";
	const redirectResponse = new Response(null, {
		status: 302,
		headers: { Location: signInUrl },
	});

	const u = await auth.api.getSession({
		headers: event.request.headers,
	});
	if (!u || !u.user || !u.session) {
		return redirectResponse;
	}
	const user = u.user as any as UserModel;
	if (user && isSignInPage) {
		return new Response(null, {
			status: 302,
			headers: { Location: baseUrl },
		});
	}
	event.locals.session = u.session;
	event.locals.user = user;

	return resolve(event);
};

export const second: Handle = createTRPCHandle({ router, createContext });

export const handle = sequence(zero, first, second);
