import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import axios from 'axios'

const options = {
  providers: [
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        username: {label: 'Email', type: 'email', placeholder: 'email@exemple.net'},
        password: {label: 'Password', type: 'password'}
      },
      authorize: async credentials => {
        try {
          const user = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/auth/local`, {
            identifier: credentials.username,
            password: credentials.password
          })
          if (user.data) {
            return user.data
          }

          return null
        } catch (error) {
          const errorMessage = error.response.data.message[0].messages[0].message
          throw new Error(errorMessage)
        }
      }
    }),
    Providers.Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET
    })
  ],
  database: process.env.NEXT_PUBLIC_DATABASE_URL,
  session: {
    jwt: true
  },
  callbacks: {
    jwt: async (token, user, account) => {
      if (user) {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_API_URL}/auth/${account.provider}/callback?access_token=${account?.accessToken}`
        )
        const data = await response.json()
        token.id = data.id || user.id
        token.jwt = data.jwt || user.jwt
        token.user = data.user || user.user
      }

      return Promise.resolve(token)
    },
    session: async (session, token) => {
      session.jwt = token.jwt
      session.user = token.user
      return Promise.resolve(session)
    }
  },
  pages: {
    signIn: '/soumet',
    error: '/soumet'
  }
}
const Auth = (request, response) =>
  NextAuth(request, response, options)
export default Auth
