import {PrismaAdapter} from '@auth/prisma-adapter'
import NextAuth from 'next-auth'
import Credentials from 'next-auth/providers/credentials'
import Github from 'next-auth/providers/github'
import Google from 'next-auth/providers/google'

//import 'server-only'
import authConfig from './auth.config'
import {
	getUserAccountByUserId,
	exisingUser as getUserById
} from '@/actions/auth/common'
import {authorizeCallback} from '@/actions/auth/login'
import {db} from '@/lib/db/prisma/client'

export const {
	auth,
	handlers: {GET, POST},
	signIn,
	signOut
} = NextAuth({
	pages: {
		signIn: '/login',
		//signOut: '/auth/signout',
		//error: '/auth/error', // Error code passed in query string as ?error=
		//verifyRequest: '/auth/verify-request', // (used for check email message)
		newUser: '/register'
	},
	trustHost: true,
	logger:
		process.env.NODE_ENV === 'development'
			? {
					// debug: console.log,
					error: console.error,
					warn: console.warn
				}
			: {error: console.error},
	debug: process.env.NODE_ENV === 'development',
	session: {strategy: 'jwt', maxAge: 48 * 60 * 60},
	...authConfig,
	adapter: PrismaAdapter(db),
	providers: [
		Google,
		Github,
		Credentials({
			name: 'credentials',
			credentials: {
				email: {label: 'Email', type: 'text'},
				password: {label: 'Пароль', type: 'password'}
			},
			async authorize(credentials): Promise<any | null> {
				return await authorizeCallback(credentials)
			}
		})
	],
	callbacks: {
		async signIn({user, account}) {
			if (account?.provider !== 'credentials') {
				return true
			}

			if (!user?.id) return false

			const exisingUser = await getUserById(user.id)

			return !Boolean(exisingUser?.emailVerified)
		},
		async jwt({token}) {
			if (!token?.sub) return token

			const exisingUser = await getUserAccountByUserId(token.sub)

			if (!exisingUser) return token

			/* eslint-disable */
			token.isOauth = exisingUser.hasOwnProperty('isOauth')
				? Boolean(exisingUser.isOauth)
				: false
			/* eslint-enable */
			token.provider = exisingUser.provider
			token.role = exisingUser.role
			token.profileId = exisingUser.profileId
			token.name = exisingUser.name
			token.username = exisingUser.username
			token.email = exisingUser.email
			token.image = exisingUser.image

			return token
		},
		async session({token, session}) {
			return {
				...session,
				user: {
					...session.user,
					id: token.sub,
					isOauth: token.isOauth,
					provider: token.provider,
					role: token.role,
					profileId: token.profileId,
					username: token.username
				}
			}
		}
	}
})
