import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { db } from "@/lib/db";
import { authConfig } from "@/lib/auth.config";

/**
 * Full Auth.js v5 configuration -- Node.js runtime only.
 * Extends auth.config.ts with the Credentials provider (needs bcryptjs + Prisma).
 */
export const { handlers, auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [
    Credentials({
      name: "credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          return null;
        }

        const email = credentials.email as string;
        const password = credentials.password as string;

        const user = await db.user.findUnique({
          where: { email },
        });

        if (!user || !user.passwordHash) {
          return null;
        }

        const isValid = await bcrypt.compare(password, user.passwordHash);

        if (!isValid) {
          return null;
        }

        // Require email verification before allowing login
        if (!user.emailVerified) {
          throw new Error("Please verify your email before signing in.");
        }

        return {
          id: user.id,
          email: user.email,
          name: user.name,
          image: user.image,
        };
      },
    }),
  ],
  callbacks: {
    ...authConfig.callbacks,
    async jwt({ token, user, trigger }) {
      if (user || trigger === "update") {
        const userId = (user?.id ?? token.id) as string;
        token.id = userId;
        const dbUser = await db.user.findUnique({
          where: { id: userId },
          select: { plan: true, teamId: true, teamRole: true },
        });
        token.plan = dbUser?.plan ?? "free";
        token.teamId = dbUser?.teamId ?? null;
        token.teamRole = dbUser?.teamRole ?? null;
      }
      return token;
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.id = token.id as string;
        const extended = session.user as unknown as Record<string, unknown>;
        extended.plan = token.plan as string;
        extended.teamId = token.teamId as string | null;
        extended.teamRole = token.teamRole as string | null;
      }
      return session;
    },
  },
});
