'use server'
import { redirect } from 'next/navigation'
import { decode } from 'decode-formdata'
import { object, string, email, minLength, safeParse } from 'valibot'
import { auth, createSession } from '@/auth/lucia'
import { valiError } from '@/lib/utils'

export const signInUser = async (_: any, formData: FormData) => {
  const data = decode(formData)
  const result = safeParse(LoginSchema, data)

  if (!result.success) {
    return valiError(result.issues)
  }
  
  const { user, err } = await signIn(result.output)

  if (err?.message.includes('AUTH_INVALID')) {
    return { password: 'Incorrect email or password' }
  }

  if (err) {
    return { message: 'An unknown error occurred' }
  }

  await createSession(user.userId)
  redirect(process.env.NEXT_PUBLIC_WEBSITE_URL ?? '/')
}

const LoginSchema = object({
  email: string([email('Please provide a valid email.')]),
  password: string([minLength(6, 'Must be atleast 6 characters long.')]),
})

export const signIn = async (data: Record<'email' | 'password', string>) => {
  try {
    console.log({ data })
    const user = await auth.useKey(
      'email',
      data.email.toLowerCase(),
      data.password
    )

    const isBanned = await prisma?.user.findFirst({ where: { id: user.userId } , select : { isBanned: true } })
    if(isBanned?.isBanned) {
      throw new Error('AUTH_BANNED')
    }
    return { user }
  } catch (err) {
    return { err: err as Error }
  }
}
