import { AuthOptions, Session } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { LOGIN_API_PATH } from "./api";

export interface SessionStaff {
  id: number;
  teamId: number;
  isTeamLead: boolean;
  employType: string | null;
  /**
   * The join date in milliseconds since epoch
   */
  joinDate: number | null;
}
export interface SessionWithTokens extends Session {
  staff?: SessionStaff;
  role?: string;
  abilities?: string[];
  accessToken?: string;
  refreshToken?: string;
  isTeamLead?: boolean;
}

export interface ability {
  actionSubjectCombo: string;
}

export const authOptions: AuthOptions = {
  debug: process.env.NODE_ENV === "development",
  providers: [
    CredentialsProvider({
      id: "credentials",
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        const res = await fetch(LOGIN_API_PATH, {
          method: "POST",
          body: JSON.stringify(credentials),
          headers: { "Content-Type": "application/json" },
        });

        const user = await res.json();

        if (res.ok && user) {
          return user;
        }
        return null;
      },
    }),
  ],
  pages: {
    signIn: "/login",
  },
  callbacks: {
    jwt(params) {
      // Add the data from user to the token
      const { token, user, account, trigger, session } = params;

      if (trigger === "update" && session?.accessToken && session?.refreshToken) {
        token.accessToken = session.accessToken
        token.refreshToken = session.refreshToken
      }

      let newToken = { ...token, ...user };

      return newToken;
    },
    session({ session, token }) {
      // console.log(token.accessToken as string | undefined)
      const sessionWithToken: SessionWithTokens = {
        ...session,
        role: token.role as string,
        // Add the data from the token to the session
        abilities: (token.abilities as ability[]).map(
          (item: ability) => item.actionSubjectCombo,
        ) as string[],
        accessToken: token.accessToken as string | undefined,
        refreshToken: token.refreshToken as string | undefined,
        staff: token.staff as SessionStaff,
      };
      // console.log(sessionWithToken)
      return sessionWithToken;
    },
  }
};
