import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "./lib/prisma";

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [GitHub],
  adapter: PrismaAdapter(prisma),
  callbacks: {
    // Add custom properties to the session object if needed
    session: async ({ session, user }) => {
      if (session.user) {
        session.user.id = user.id;
      }
      return session;
    },
  },
  events: {
    // This ensures user profile data is properly updated
    // when they sign in with GitHub or other providers
    async signIn({ user, account, profile }) {
      if (account?.provider === "github" && profile) {
        try {
          // Update or ensure GitHub-specific user data is saved
          await prisma.user.update({
            where: { id: user.id },
            data: {
              name: profile.name ?? user.name,
              image: profile.avatar_url ?? user.image,
              // Add any other profile data you want to store
            },
          });
        } catch (error) {
          console.error("Error updating user data:", error);
        }
      }
    },
  },
});
