import type { NextAuthOptions } from "next-auth";
import Google from "next-auth/providers/google";
import Apple from "next-auth/providers/apple";
import Credentials from "next-auth/providers/credentials";
import { checkAuth } from "./opensearch";

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: "Link",
      credentials: {
        authToken: { label: "AuthToken", type: "text", },
      },
      async authorize(credentials, req) {
        const { headers } = req;
        console.log({ headers });
        const leafcutterUser = headers?.["x-leafcutter-user"];
        const authToken = credentials?.authToken;

        if (!leafcutterUser || leafcutterUser.trim() === "") {
          console.log("no leafcutter user");
          return null;
        }

        console.log({ authToken });
        return null;
        /*
        try {
          // add role check
          await checkAuth(username, password);
          const user = {
            id: leafcutterUser,
            email: leafcutterUser
          };

          return user;
        } catch (e) {
          console.log({ e });
        }

        return null;
        */
      }
    })

  ],
  secret: process.env.NEXTAUTH_SECRET,
  /*
  callbacks: {
    signIn: async ({ user, account, profile }) => {
      const roles: any = [];
      return roles.includes("admin") || roles.includes("agent");
    },
    session: async ({ session, user, token }) => {
      // @ts-ignore
      session.user.roles = token.roles;
      return session;
    },
    jwt: async ({ token, user, account, profile, trigger }) => {
      if (user) {
        token.roles = [];
      }
      return token;
    }
  },*/
};

