import axios from "axios";
import { AuthOptions } from "next-auth";
import { JWT } from "next-auth/jwt";
import CredentialsProvider from "next-auth/providers/credentials";

interface IToken {
  access: string;
}

const refreshToken = async (token: JWT): Promise<JWT> => {
  const data = {
    refresh: token.refresh_token,
  };

  const response = await axios.post<IToken>(
    "https://api.kgroad.org/api/v1/token/refresh/",
    data
  );

  return {
    ...token,
    access_token: response.data.access,
  };
};

export const authConfig: AuthOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",

      credentials: {
        email: {
          label: "Email",
          type: "text",
          placeholder: "jsmith@example.com",
        },
        password: { label: "Password", type: "password" },
      },

      async authorize(credentials, req) {
        if (!credentials?.email || !credentials?.password)
          return null;

        const { email, password } = credentials as any;

        const res = await fetch(
          "https://api.kgroad.org/api/v1/users/login/",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              email,
              password,
            }),
          }
        );

        if (res.status.toString()[0] === "4") {
          return null;
        }

        const user = await res.json();
        return user;
      },
    }),
  ],
  pages: {
    signIn: "/sign-in",
  },
  session: {
    strategy: "jwt",
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) return { ...token, ...user };

      return refreshToken(token);
    },

    async session({ token, session }) {
      session.access_token = token.access_token;
      session.refresh_token = token.refresh_token;

      return session;
    },
  },
};
