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

// import { env } from "$env/dynamic/private";
// import { withOpenTelemetry } from "@baselime/sveltekit-opentelemetry-middleware";
// import { BaselimeSDK } from "@baselime/node-opentelemetry";

// const appName = "domain-wall_enduser";

// const sdk = new BaselimeSDK({
// 	collectorUrl: env.OTEL_COLLECTOR_URL,
// 	serverless: false,
// 	service: appName,
// 	baselimeKey: "some-rando-ahh-key",
// });
// sdk.start();

// const meter = metrics.getMeter(appName);

// export const genesis = withOpenTelemetry(
// 	async ({ event, resolve }) => resolve(event),
// 	// { requestIdHeader: "x-request-id" },
// );

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 isSignInPage = event.url.pathname === "/auth/login";

	const u = await auth.api.getSession({ headers: event.request.headers });
	const user = u?.user as any as UserModel;
	if (user && isSignInPage) {
		return new Response(null, {
			status: 302,
			headers: { Location: baseUrl },
		});
	}
	// @ts-ignore
	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);

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