import { useMutation, useQuery } from '@tanstack/vue-query'

import {
  apiCompleteProfile,
  apiForgotPassword,
  apiGetMe,
  apiGetRegisterData,
  apiGetRegistrationQuestionVideo,
  apiLogin,
  apiRequestLoginOtp,
  apiVerifyLoginOtp,
  apiLogout,
  apiRegister,
  apiResendVerificationCode,
  apiResetPassword,
  apiSaveRegisterData,
  apiUpdateProfile,
  apiUploadMedia,
  apiVerifyCode,
  apiVerifyForgotPasswordCode,
} from '@/services/api/auth'

export const authKeys = {
  me: () => ['auth', 'me'],
  registrationVideo: () => ['auth', 'registration-video'],
  registerData: () => ['auth', 'register-data'],
}

export const useLoginMutation = () => useMutation({ mutationFn: apiLogin })

export const useRequestLoginOtpMutation = () => useMutation({ mutationFn: apiRequestLoginOtp })

export const useVerifyLoginOtpMutation = () => useMutation({ mutationFn: apiVerifyLoginOtp })

export const useRegisterMutation = () => useMutation({ mutationFn: apiRegister })

export const useVerifyCodeMutation = () => useMutation({ mutationFn: apiVerifyCode })

export const useResendVerificationCodeMutation = () =>
  useMutation({ mutationFn: apiResendVerificationCode })

export const useForgotPasswordMutation = () => useMutation({ mutationFn: apiForgotPassword })

export const useVerifyForgotPasswordCodeMutation = () =>
  useMutation({ mutationFn: apiVerifyForgotPasswordCode })

export const useResetPasswordMutation = () => useMutation({ mutationFn: apiResetPassword })

export const useLogoutMutation = () => useMutation({ mutationFn: apiLogout })

export const useGetMeQuery = (options = {}) =>
  useQuery({
    queryKey: authKeys.me(),
    queryFn: () => apiGetMe(),
    select: (response) => response?.data ?? response,
    ...options,
  })

export const useCompleteProfileMutation = () => useMutation({ mutationFn: apiCompleteProfile })

export const useUpdateProfileMutation = () => useMutation({ mutationFn: apiUpdateProfile })

const getRegistrationVideoIfAvailable = async () => {
  try {
    return await apiGetRegistrationQuestionVideo()
  } catch (error) {
    // The migrated backend does not expose this optional content endpoint yet.
    // Treat a missing route as "no tutorial uploaded" so registration remains usable.
    if (error?.response?.status === 404) return {}
    throw error
  }
}

export const useGetRegistrationVideoQuery = (options = {}) =>
  useQuery({
    queryKey: authKeys.registrationVideo(),
    queryFn: getRegistrationVideoIfAvailable,
    select: (response) => response?.data ?? response,
    ...options,
  })

export const useUploadMediaMutation = () => useMutation({ mutationFn: apiUploadMedia })

// Register-data is a flat `{ field: value }` object; legacy responses were a
// `[{ key, value }]` list. Normalize both into the object shape.
const toRegisterDataObject = (response) => {
  const body = response?.data ?? response
  const raw = Array.isArray(body) ? body : body?.data ?? body
  if (Array.isArray(raw)) {
    return raw.reduce((acc, item) => {
      if (item && typeof item === 'object' && 'key' in item) acc[item.key] = item.value
      return acc
    }, {})
  }
  return raw && typeof raw === 'object' ? raw : {}
}

export const useGetRegisterDataQuery = (options = {}) =>
  useQuery({
    queryKey: authKeys.registerData(),
    queryFn: () => apiGetRegisterData(),
    select: toRegisterDataObject,
    ...options,
  })

export const useSaveRegisterDataMutation = () => useMutation({ mutationFn: apiSaveRegisterData })
