import { AuthOptions, getServerSession as getNextAuthServerSession } from "next-auth";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import Credentials from "next-auth/providers/credentials";
import { prisma, PrismaClient } from "@repo/db";

export const options: AuthOptions = {
	providers: [
		Credentials({
			credentials: {
				code: { label: "code", type: "code" },
			},
			async authorize(credentials, req) {
				try {
					if (!credentials) throw new Error("No credentials provided");
					const code = await prisma.oAuthToken.findFirstOrThrow({
						where: {
							accessToken: credentials.code,
						},
					});
					const user = await prisma.user.findFirstOrThrow({
						where: {
							id: code.userId,
						},
					});

					if (!user) return null;

					return user;
				} catch (error) {
					console.error(error);
					return null;
				}
			},
		}),
	],
	secret: process.env.AUTH_DISPATCH_SECRET,
	cookies: {
		sessionToken: {
			name: `${process.env.AUTH_DISPATCH_COOKIE_PREFIX}-next-auth.session-token`, // Ändere den Namen für App 1
			options: {
				httpOnly: true,
				secure: process.env.NODE_ENV === "production",
				path: "/",
			},
		},
		csrfToken: {
			name: `${process.env.AUTH_DISPATCH_COOKIE_PREFIX}-next-auth.csrf-token`,
			options: {
				httpOnly: true,
				secure: process.env.NODE_ENV === "production",
				path: "/",
			},
		},
	},

	session: {
		strategy: "jwt",
		maxAge: 30 * 24 * 60 * 60,
	},

	adapter: PrismaAdapter(prisma as any),
	callbacks: {
		jwt: async ({ token, user, ...rest }) => {
			if (user && "firstname" in user) {
				return {
					...token,
					...user,
				};
			}
			return token;
		},
		session: async ({ session, user, token }) => {
			const dbUser = await prisma.user.findUnique({
				where: {
					id: token?.sub,
				},
			});
			if (!dbUser) {
				return {
					...session,
					user: {
						name: null,
						email: null,
						image: null,
					},
					expires: new Date().toISOString(),
				};
			}
			return {
				...session,
				user: dbUser,
			};
		},
	},
	pages: {
		signIn: "/login",
		signOut: "/logout",
		error: "/authError",
	},
} satisfies AuthOptions;

export const getServerSession = async () => getNextAuthServerSession(options);
