import NextAuth from "next-auth";
import type { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { getAuthUser } from "@/services/public";

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      // The name to display on the sign in form (e.g. "Sign in with...")
      name: "Credentials",
      // `credentials` is used to generate a form on the sign in page.
      // You can specify which fields should be submitted, by adding keys to the `credentials` object.
      // e.g. domain, username, password, 2FA token, etc.
      // You can pass any HTML attribute to the <input> tag through the object.
      credentials: {},
      async authorize(credentials, req) {
        const STAGING_PATH = process.env.NEXT_STAGING_DIR_PATH || '';
        // Add logic here to look up the user from the credentials supplied
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_API_BASE_URL}${STAGING_PATH}/api/v1/login`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              username: req?.body?.username,
              password: req?.body?.password,
            }),
            cache: "default",
          },
        );
  

        const responseData = await response.json();
        if (responseData.status == "success") {
          return {
            id: responseData.data.id,
            name: responseData?.data?.role_id,
            email: responseData.data.username,
            image: responseData.data.access_token,
          };
        } else {
          throw new Error(JSON.stringify(responseData.message));
          // If you return null then an error will be displayed advising the user to check their details.
          // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
        }
      },
    }),
  ],
  // use env variable in production
  secret: process.env.NEXT_PUBLIC_JWT_SECRET,
  callbacks: {
    async session({ session }) {
      if (session.user) {
        const token = session.user?.image;
        const userInfo = await getAuthUser(token);
        let userData = userInfo?.data;
        userData.image = token;
        userData.role_id = session?.user?.name;
        session.user = userData;
      }
      return session;
    },
    async jwt({ token }) {
      return token;
    },
  },
};

export default NextAuth(authOptions);
