import type { NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";

// Edge/runtime-safe Auth.js config — NO db client, NO argon2 imports.
// This is imported by the proxy/middleware entry so that the native Argon2
// module cannot leak into the Edge bundle. The full config in ./auth.ts
// spreads this object and adds the DB adapter + the real Credentials
// authorize() implementation used by the route handler.
export const authConfig: NextAuthConfig = {
  trustHost: true,
  pages: { signIn: "/login" },
  session: { strategy: "jwt", maxAge: 30 * 24 * 60 * 60, updateAge: 24 * 60 * 60 },
  logger: {
    error(err) {
      // Silence stale-cookie noise — callers already treat failed decrypt as "no session".
      // Reason: rotating AUTH_SECRET or clearing dev DB leaves old JWTs in the browser;
      // NextAuth rejects + logs before our .catch() runs. Nothing actionable for us.
      if (err?.name === "JWTSessionError") return;
      console.error(err);
    },
    warn() {},
    debug() {},
  },
  providers: [
    // Placeholder provider. The real authorize() lives in ./auth.ts.
    // Proxy/middleware only needs the JWT cookie to be read — it never
    // calls authorize().
    Credentials({
      credentials: { email: {}, password: {} },
      async authorize() {
        return null;
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        const u = user as { id?: string; role?: string };
        if (u.id) token.sub = u.id;
        if (u.role) (token as { role?: string }).role = u.role;
      }
      return token;
    },
    async session({ session, token }) {
      if (session.user) {
        (session.user as { id?: string }).id = token.sub;
        (session.user as { role?: string }).role =
          (token as { role?: string }).role ?? "user";
      }
      return session;
    },
  },
};
