import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import type { NextAuthConfig } from "next-auth";

// Note: Prisma is imported dynamically inside authorize() to avoid
// being bundled into the Edge runtime used by middleware.
async function findUserByEmail(email: string) {
  try {
    const { db } = await import("@/lib/db");
    return db.user.findUnique({
      where: { email },
      select: { id: true, email: true, passwordHash: true, firstName: true, lastName: true, role: true, isActive: true },
    });
  } catch {
    return null;
  }
}

export type UserRole = "SUPER_ADMIN" | "ADMIN" | "INSTRUCTOR" | "STUDENT";

export const authConfig: NextAuthConfig = {
  pages: {
    signIn: "/login",
    error: "/login",
  },
  session: {
    strategy: "jwt",
    maxAge: 30 * 24 * 60 * 60, // 30 days
  },
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user;
      const isAdminRoute = nextUrl.pathname.startsWith("/admin");
      const protectedPaths = ["/dashboard", "/my-account", "/checkout"];
      const isProtected = protectedPaths.some((p) => nextUrl.pathname.startsWith(p));

      if (isAdminRoute) {
        if (!isLoggedIn) return false;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const role = (auth?.user as any)?.role as UserRole;
        return role === "SUPER_ADMIN" || role === "ADMIN";
      }
      if (isProtected && !isLoggedIn) return false;
      return true;
    },

    jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        token.role = (user as any).role;
        token.firstName = (user as any).firstName;
        token.lastName = (user as any).lastName;
      }
      return token;
    },

    session({ session, token }) {
      if (token && session.user) {
        session.user.id = token.id as string;
        (session.user as any).role = token.role;
        (session.user as any).firstName = token.firstName;
        (session.user as any).lastName = token.lastName;
      }
      return session;
    },
  },

  providers: [
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Parola", type: "password" },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) return null;

        try {
          // ─── Real DB Query via Prisma (dynamic import avoids Edge bundling) ──
          const user = await findUserByEmail(credentials.email as string);

          if (!user || !user.isActive) return null;

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

          if (!isValid) return null;

          return {
            id: user.id,
            email: user.email,
            name: `${user.firstName} ${user.lastName}`,
            firstName: user.firstName,
            lastName: user.lastName,
            role: user.role,
          };
        } catch (error) {
          // DB not connected yet (setup not done) — fallback to dev seeds
          console.warn("[Auth] DB unavailable, falling back to dev seeds:", error);

          const DEV_SEEDS = [
            {
              id: "dev-1",
              email: "admin@rima-academy.com",
              passwordHash: "$2a$12$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", // secret
              firstName: "Nazjar",
              lastName: "Admin",
              role: "SUPER_ADMIN",
              isActive: true,
            },
            {
              id: "dev-2",
              email: "student@rima-academy.com",
              passwordHash: "$2a$12$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi",
              firstName: "Elena",
              lastName: "Popescu",
              role: "STUDENT",
              isActive: true,
            },
          ];

          // Simple plaintext fallback for dev
          if (credentials.email === "admin@rima-academy.com" && credentials.password === "admin1234") {
            const u = DEV_SEEDS[0];
            return { id: u.id, email: u.email, name: `${u.firstName} ${u.lastName}`, firstName: u.firstName, lastName: u.lastName, role: u.role };
          }
          if (credentials.email === "student@rima-academy.com" && credentials.password === "student1234") {
            const u = DEV_SEEDS[1];
            return { id: u.id, email: u.email, name: `${u.firstName} ${u.lastName}`, firstName: u.firstName, lastName: u.lastName, role: u.role };
          }

          return null;
        }
      },
    }),
  ],
};

export const { handlers, auth, signIn, signOut } = NextAuth(authConfig);
