// src/auth.ts
import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
import authConfig from "./auth.config";

export const { handlers, signIn, signOut, auth } = NextAuth({
  adapter: PrismaAdapter(prisma),
  session: { strategy: "jwt" },
  ...authConfig, // This now spreads the default export from auth.config.ts
  callbacks: {
    async jwt({ token, account, user }) {
      if (account) {
        token.accessToken = account.access_token;
        token.refreshToken = account.refresh_token;
        token.expiresAt = account.expires_at;
      }

      if (user) {
        token.sub = user.id;
        // @ts-ignore
        token.role = user.role;
      }

      return token;
    },

    async session({ session, token }) {
      if (session?.user) {
        session.user.id = token.sub as string;
        // @ts-ignore
        session.user.role = token.role as string;
        session.accessToken = token.accessToken as string;
      }
      return session;
    },
  },
  
  events: {
    async linkAccount({ account, user }) {
      console.log("🔗 Account linked successfully for user:", user.id);
      if (!account.refresh_token) {
        console.warn("⚠️ WARNING: No refresh_token received!");
      }
    }
  }
});