import NextAuth from 'next-auth';
import Keycloak from 'next-auth/providers/keycloak';

const keycloakInternalUrl = process.env.KEYCLOAK_URL!;
const keycloakPublicUrl = process.env.NEXT_PUBLIC_KEYCLOAK_URL!;
const realm = process.env.KEYCLOAK_REALM!;

const internalBase = `${keycloakInternalUrl}/realms/${realm}`;
const publicBase = `${keycloakPublicUrl}/realms/${realm}`;

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Keycloak({
      clientId: process.env.KEYCLOAK_CLIENT_ID!,
      clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,
      // issuer must match KC_HOSTNAME_URL so iss claim validation passes
      issuer: publicBase,
      // auth.js calls oauth4webapi.discoveryRequest(issuer) which constructs the URL from
      // `issuer` directly — our `wellKnown` override is ignored in that code path.
      // Bypass discovery entirely by pre-supplying all endpoints:
      //   - authorization uses the public URL (browser redirect)
      //   - token/userinfo/jwks use the internal Docker hostname (server-side fetches)
      // These values match what KC_HOSTNAME_URL would return in the discovery document anyway.
      authorization: `${publicBase}/protocol/openid-connect/auth`,
      token: `${internalBase}/protocol/openid-connect/token`,
      userinfo: `${internalBase}/protocol/openid-connect/userinfo`,
      jwks_endpoint: `${internalBase}/protocol/openid-connect/certs`,
    }),
  ],
  pages: {
    signIn: '/login',
  },
  callbacks: {
    async jwt({ token, account }) {
      if (account) {
        token.accessToken = account.access_token;
        token.refreshToken = account.refresh_token;
        token.expiresAt = account.expires_at;
      }
      return token;
    },
    async session({ session, token }) {
      session.accessToken = token.accessToken as string;
      return session;
    },
  },
});
