'use server'

import { signIn } from '@/auth'
import { User } from '@/lib/types'
import { AuthError } from 'next-auth'
import { z } from 'zod'
import { kv } from '@vercel/kv'
import { ResultCode } from '@/lib/utils'
import service, { UserDataStorageName } from '@/lib/http/service'
import md5 from 'md5'
import { Lekton } from 'next/font/google'

export async function getUser(email: string) {
  const user = await kv.hgetall<User>(`user:${email}`)
  return user
}

interface Result {
  type: string
  resultCode: ResultCode
}

export async function authenticate(
  _prevState: Result | undefined,
  formData: FormData
): Promise<Result | undefined> {
  try {
    const email = formData.get('email')
    const password = formData.get('password')

    console.log("---authenticate-------", email, password)

    const parsedCredentials = z
      .object({
        email: z.string().email(),
        password: z.string().min(6)
      })
      .safeParse({
        email,
        password
      })

    if (parsedCredentials.success) {
      // await signIn('credentials', {
      //   email,
      //   password,
      //   redirect: false
      // })

      // return {
      //   type: 'success',
      //   resultCode: ResultCode.UserLoggedIn
      // }

      await service.post('/api/v1/customer/login', {
        user_name: email,
        password: md5(password as string),

      }).then(function (result: any) {
        console.log("result:", result)

        if (result && result.header.code != 0) {

          // toast.error(result.header.message)
          return {
            type: 'error',
            resultCode: ResultCode.InvalidCredentials
          }
        }

        localStorage.setItem(UserDataStorageName, JSON.stringify(result.data));
        // []方法
        { {/* localStorage["name"]="bonly"; */ } }

        // router.push("/");
        window.location.href = `/`

      }).catch((err) => {
        console.log(err);

        return {
          type: 'error',
          resultCode: ResultCode.InvalidCredentials
        }

      });
    } else {
      return {
        type: 'error',
        resultCode: ResultCode.InvalidCredentials
      }
    }
  } catch (error) {
    if (error instanceof AuthError) {
      switch (error.type) {
        case 'CredentialsSignin':
          return {
            type: 'error',
            resultCode: ResultCode.InvalidCredentials
          }
        default:
          return {
            type: 'error',
            resultCode: ResultCode.UnknownError
          }
      }
    }
  }
}
