import { checkInitial2FaRequired } from "@pkg/logic/domains/2fa/sensitive-actions";
import type { Handle, HandleServerError } from "@sveltejs/kit";
import { auth } from "@pkg/logic/domains/auth/config.base";
import { svelteKitHandler } from "better-auth/svelte-kit";
import type { User } from "@pkg/logic/domains/user/data";
import { sequence } from "@sveltejs/kit/hooks";
import { building } from "$app/environment";

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, building });
};

export const first: Handle = async ({ event, resolve }) => {
    if (
        event.url.pathname.includes("/api/v1") ||
        event.url.pathname.includes("/api/auth") ||
        event.url.pathname.includes("/api/debug") ||
        event.url.pathname.includes("/api/chat") ||
        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;
    }
    if (u.user && isSignInPage) {
        return new Response(null, {
            status: 302,
            headers: { Location: baseUrl },
        });
    }

    console.log("Setting user & session to locals");

    const fid = crypto.randomUUID();

    event.locals.flowId = fid;
    event.locals.session = u.session;
    event.locals.user = u.user as any as User;

    const needs2FA = await checkInitial2FaRequired(
        {
            flowId: fid,
            userId: u.user.id,
            sessionId: u.session.id,
        },
        u.user as any,
        u.session.id,
    );
    if (needs2FA && !event.url.pathname.includes("/auth/2fa")) {
        return new Response(null, {
            status: 302,
            headers: {
                Location: `/auth/2fa?redirect=${encodeURIComponent(event.url.pathname)}`,
            },
        });
    }

    return resolve(event);
};

export const handle = sequence(zero, first);
