import NextAuth from "next-auth";
import Authentik from "next-auth/providers/authentik";
import { findOrCreateUser } from "@/lib/users";

type AuthentikProfile = {
  groups?: unknown;
  name?: unknown;
  email?: unknown;
};

export const { handlers, auth, signIn, signOut } = NextAuth({
  trustHost: true,
  providers: [
    Authentik({
      issuer: process.env.AUTHENTIK_ISSUER,
      clientId: process.env.AUTHENTIK_CLIENT_ID,
      clientSecret: process.env.AUTHENTIK_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    async jwt({ token, profile }) {
      if (profile) {
        const authentikProfile = profile as AuthentikProfile;
        const groups = Array.isArray(authentikProfile.groups)
          ? authentikProfile.groups.filter((group): group is string => typeof group === "string")
          : [];
        const isAdmin = groups.includes("sticknife_admins");

        // Create or update the local user record on each sign-in.
        const localUserId = await findOrCreateUser({
          externalId: token.sub!,
          provider: "authentik",
          name: typeof authentikProfile.name === "string" ? authentikProfile.name : token.sub!,
          email: typeof authentikProfile.email === "string" ? authentikProfile.email : "",
          isAdmin,
        });

        token.localUserId = localUserId;
        token.groups = groups;
        token.isAdmin = isAdmin;
      }
      return token;
    },
    async session({ session, token }) {
      session.user.id = token.localUserId as string;
      session.user.groups = token.groups as string[];
      session.user.isAdmin = token.isAdmin as boolean;
      return session;
    },
  },
  pages: {
    signIn: "/login",
    error: "/auth-error",
  },
});
