import { cleanFilters } from '@/utils/clean-filters'
import { useMutation, useQuery } from '@tanstack/vue-query'
import {
  apiAddAdminUser,
  apiChangeAdminUserStatus,
  apiDeleteAdminUser,
  apiGetAdminUserRegisterData,
  apiGetAdminUsers,
  apiShowAdminUser,
  apiUpdateAdminUser,
  apiUpdateAdminUserRole,
} from '@/services/api/admin-users'

export const adminUsersKeys = {
  all: ['admin', 'users'],
  list: (filters, pagination) => ['admin', 'users', 'list', filters, pagination],
  detail: (id) => ['admin', 'users', 'detail', id],
  registerData: (id) => ['admin', 'users', 'register-data', id],
}

export const useAdminUsersListQuery = (filtersRef, paginationRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'users', 'list', filtersRef, paginationRef],
    queryFn: () => apiGetAdminUsers({ ...cleanFilters(filtersRef.value), ...paginationRef.value }),
    select: (response) => ({
      data: response?.data?.items ?? response?.data ?? [],
      meta: response?.data?.meta ?? response?.meta,
    }),
    ...options,
  })

export const useAdminUserQuery = (idRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'users', 'detail', idRef],
    queryFn: () => apiShowAdminUser(idRef.value),
    select: (response) => response?.data ?? response,
    ...options,
  })

// Register-data comes back as a `[{ key, value }]` array (values may be
// strings, numbers, null, or nested objects/arrays). Normalize it into a plain
// `{ key: value }` object for consumers; tolerate an already-object shape too.
const toRegisterDataObject = (response) => {
  const raw = response?.data ?? response
  if (Array.isArray(raw)) {
    return raw.reduce((acc, item) => {
      if (item && item.key != null) acc[item.key] = item.value
      return acc
    }, {})
  }
  return raw || {}
}

export const useAdminUserRegisterDataQuery = (idRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'users', 'register-data', idRef],
    queryFn: () => apiGetAdminUserRegisterData(idRef.value),
    select: toRegisterDataObject,
    ...options,
  })

export const useAddAdminUserMutation = () =>
  useMutation({ mutationFn: (payload) => apiAddAdminUser(payload) })

export const useUpdateAdminUserMutation = () =>
  useMutation({ mutationFn: ({ id, payload }) => apiUpdateAdminUser(id, payload) })

export const useUpdateAdminUserRoleMutation = () =>
  useMutation({ mutationFn: ({ id, payload }) => apiUpdateAdminUserRole(id, payload) })

export const useChangeAdminUserStatusMutation = () =>
  useMutation({ mutationFn: ({ id, payload }) => apiChangeAdminUserStatus(id, payload) })

export const useDeleteAdminUserMutation = () =>
  useMutation({ mutationFn: (id) => apiDeleteAdminUser(id) })
