import type { NextAuthConfig } from "next-auth";

/**
 * Edge-compatible auth config — no DB imports.
 * Used by middleware.ts (Edge Runtime).
 * Full auth.ts adds the Credentials provider with DB access.
 */
export const authConfig = {
  session: {
    strategy: "jwt",
    maxAge: 7 * 24 * 60 * 60,
    updateAge: 24 * 60 * 60,
  },
  pages: {
    signIn: "/agent/login",
  },
  providers: [], // Providers added in auth.ts — not needed for middleware JWT check
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user;
      const isLoginPage = nextUrl.pathname === "/agent/login";
      const isAgentRoute = nextUrl.pathname.startsWith("/agent");
      const isPortalRoute = nextUrl.pathname.startsWith("/portal");

      if (isLoginPage) {
        if (isLoggedIn) return Response.redirect(new URL("/portal/dashboard", nextUrl.origin));
        return true; // Always allow unauthenticated access to login page
      }

      if (isAgentRoute) {
        return isLoggedIn; // Redirect unauthenticated users to login
      }

      if (isPortalRoute) {
        if (!isLoggedIn) return Response.redirect(new URL("/agent/login", nextUrl));
      }

      return true;
    },
    jwt({ token, user }) {
      if (user) token.id = user.id;
      return token;
    },
    session({ session, token }) {
      session.user.id = token.id as string;
      return session;
    },
  },
} satisfies NextAuthConfig;
