import NextAuth, { type NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import MicrosoftEntraID from "next-auth/providers/microsoft-entra-id";

const providers: NextAuthConfig["providers"] = [];

if (
  process.env.AUTH_MICROSOFT_ENTRA_ID_ID &&
  process.env.AUTH_MICROSOFT_ENTRA_ID_SECRET
) {
  providers.push(
    MicrosoftEntraID({
      clientId: process.env.AUTH_MICROSOFT_ENTRA_ID_ID,
      clientSecret: process.env.AUTH_MICROSOFT_ENTRA_ID_SECRET,
      issuer: process.env.AUTH_MICROSOFT_ENTRA_ID_ISSUER,
    }),
  );
}

if (process.env.DEV_PORTAL_PASSWORD) {
  providers.push(
    Credentials({
      id: "dev",
      name: "Development access",
      credentials: {
        password: { label: "Access password", type: "password" },
      },
      authorize: async (credentials) => {
        const supplied =
          typeof credentials?.password === "string" ? credentials.password : "";
        if (supplied && supplied === process.env.DEV_PORTAL_PASSWORD) {
          return {
            id: "dev-user",
            name: "Developer",
            email: "dev@portal.local",
          };
        }
        return null;
      },
    }),
  );
}

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers,
  pages: {
    signIn: "/login",
  },
  session: { strategy: "jwt" },
  trustHost: true,
});
