import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import axios from 'axios'

const options = {
  providers: [
    CredentialsProvider({
      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)
        }
      }
    })
  ],
  secret: process.env.NEXT_PUBLIC_JWT_SECRET,
  session: {
    strategy: 'jwt'
  },
  pages: {
    signIn: '/soumet',
    error: '/soumet'
  }
}
const Auth = (request, response) =>
  NextAuth(request, response, options)
export default Auth
