import NextAuth, { User } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import axios from "axios";
import { jwtDecode } from "jwt-decode";

const handler = NextAuth({
    providers: [
        Credentials({
            credentials: {
                email: {},
                password: {},
            },
            async authorize(credentials) {
                try {
                    const response = await axios.post(
                        'https://private-docs-api.intside.co/users/login/',
                        {
                            email: credentials?.email,
                            password: credentials?.password,
                        }
                    )

                    const { access_token, refresh_token } = response.data;
                    const { id } = jwtDecode(access_token) as { id: string };

                    return {
                        id: id,
                        email: credentials?.email,
                        access_token: access_token,
                        refresh_token: refresh_token
                    } as User;
                } catch (error) {
                    if (axios.isAxiosError(error)) {
                        if (error.response?.status === 401) {
                            throw new Error("Email ou mot de passe incorrect");
                        }
                        throw new Error(error.response?.data?.message || error.message);
                    }
                    throw new Error("Une erreur est survenue");
                }
            },
        })
    ],
    session: {
        strategy: "jwt",
    },
    callbacks: {
        async jwt({ token, user }) {
            if (user) {
                token.access_token = user.access_token;
                token.refresh_token = user.refresh_token;
            }
            return token;
        },
        async session({ session, token }) {
            return {
              ...session,
              user: {
                ...session.user,
                ...token,
              },
            };
          },
    },
    secret: process.env.AUTH_SECRET ?? "",
});

export { handler as GET, handler as POST };
