import { zodResolver } from '@hookform/resolvers/zod'
import { data } from 'react-router'
import { getValidatedFormData } from 'remix-hook-form'
import { XiorError } from 'xior'

import { getStaff } from '~/apis/admin/get-staff'
import { staffLoginRequest } from '~/apis/admin/login-staff'
import { loginSchema, type TLoginSchema } from '~/pages/admin-login'
import { generateStaffTokenCookie } from '~/utils/token'

import type { Route } from './+types/actions.login'

export const action = async ({ request }: Route.ActionArgs) => {
  try {
    const {
      errors,
      data: payload,
      receivedValues: defaultValues,
    } = await getValidatedFormData<TLoginSchema>(
      request,
      zodResolver(loginSchema),
      false,
    )

    if (errors) {
      return data({ success: false, errors, defaultValues }, { status: 400 })
    }

    const { data: loginData } = await staffLoginRequest(payload)
    const { token } = loginData
    const { data: staffData } = await getStaff({
      accessToken: token,
    })
    const tokenCookie = generateStaffTokenCookie({
      token,
    })

    const headers = new Headers()
    headers.append('Set-Cookie', await tokenCookie)

    return data(
      {
        success: true,
        staff: staffData,
      },
      {
        headers,
        status: 200,
        statusText: 'OK',
      },
    )
  } catch (error) {
    if (error instanceof XiorError) {
      return data(
        {
          success: false,
          message: error?.response?.data?.error?.message || error.message,
        },
        {
          status: error?.response?.status || 500,
        },
      )
    }
    return data(
      {
        success: false,
        message: 'Internal server error',
      },
      { status: 500 },
    )
  }
}
