import type {
  GetServerSidePropsContext,
  NextApiRequest,
  NextApiResponse,
} from "next";
import {
  NextAuthOptions,
  getServerSession as internalGetServerSession,
} from "next-auth";
import Google from "next-auth/providers/google";
import Credentials from "next-auth/providers/credentials";
import Apple from "next-auth/providers/apple";

const headers = { Authorization: `Token ${process.env.ZAMMAD_API_TOKEN}` };

const fetchRoles = async () => {
  const url = `${process.env.ZAMMAD_URL}/api/v1/roles`;
  const res = await fetch(url, { headers });
  const roles = await res.json();
  console.log({ roles });
  const formattedRoles = roles.reduce((acc: any, role: any) => {
    acc[role.id] = role.name;
    return acc;
  }, {});
  return formattedRoles;
};

const fetchUser = async (email: string) => {
  console.log({ email });
  const url = `${process.env.ZAMMAD_URL}/api/v1/users/search?query=login:${email}&limit=1`;
  console.log({ url });
  const res = await fetch(url, { headers });
  console.log({ res });
  const users = await res.json();
  console.log({ users });
  const user = users?.[0];

  return user;
};

const getUserRoles = async (email: string) => {
  try {
    const user = await fetchUser(email);
    console.log({ user });
    const allRoles = await fetchRoles();
    console.log({ allRoles });
    const roles = user.role_ids.map((roleID: number) => {
      const role = allRoles[roleID];
      return role ? role.toLowerCase().replace(" ", "_") : null;
    });
    return roles.filter((role: string) => role !== null);
  } catch (e) {
    console.log({ e });
    return [];
  }
};

const login = async (email: string, password: string) => {
  const url = `${process.env.ZAMMAD_URL}/api/v1/users/me`;
  console.log({ url });
  const authorization =
    "Basic " + Buffer.from(email + ":" + password).toString("base64");
  const res = await fetch(url, {
    headers: {
      authorization,
    },
  });
  const user = await res.json();
  console.log({ user });

  if (user && !user.error && user.id) {
    return user;
  } else {
    return null;
  }
};

export const authOptions: NextAuthOptions = {
  pages: {
    signIn: "/login",
    error: "/login",
    signOut: "/logout",
  },
  providers: [
    Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    Apple({
      clientId: process.env.APPLE_CLIENT_ID,
      clientSecret: process.env.APPLE_CLIENT_SECRET,
    }),
    Credentials({
      name: "Zammad",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        const user = await login(credentials.email, credentials.password);
        if (user) {
          return user;
        } else {
          return null;
        }
      },
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
    signIn: async ({ user, account, profile }) => {
      const roles = (await getUserRoles(user.email)) ?? [];
      return (
        roles.includes("admin") ||
        roles.includes("agent") ||
        process.env.SETUP_MODE === "true"
      );
    },
    session: async ({ session, user, token }) => {
      // @ts-ignore
      session.user.roles = token.roles ?? [];
      // @ts-ignore
      session.user.leafcutter = token.leafcutter; // remove
      return session;
    },
    jwt: async ({ token, user, account, profile, trigger }) => {
      if (user) {
        token.roles = (await getUserRoles(user.email)) ?? [];
      }
      return token;
    },
  },
}

export const getServerSession = (
  ...args:
    | [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]]
    | [NextApiRequest, NextApiResponse]
    | []
) => internalGetServerSession(...args, authOptions);
