import { auth } from "$lib/domains/auth/config/base";
import { UserController } from "$lib/domains/user/domain/controller";
import type { RequestEvent } from "@sveltejs/kit";
import type { inferAsyncReturnType } from "@trpc/server";

export async function createContext(event: RequestEvent) {
	const headers = event.request.headers;
	const result = await auth.api.getSession({ headers });

	if (!result || !result.user || !result.session) {
		return { headers };
	}

	const uc = new UserController();
	const uOut = await uc.getUserById(result.user.id);
	if (uOut.error) {
		return { headers };
	}

	return { session: result.session, user: uOut.data, headers };
}

export type Context = inferAsyncReturnType<typeof createContext>;
