import { matchPath, useLocation } from 'react-router-dom'

import { getBFFTiDB } from 'dbaas/features/ClusterManagement/tidb'
import { useTiDBServiceGetTidb } from 'dbaas/services/api-clients/v2023/cluster-management/v1beta2'
import useStores from 'dbaas/stores/useStores'

export const useGetCurrentTidbId = () => {
  const location = useLocation()
  const match = matchPath<{ id: string }>(location.pathname, {
    path: '/tidbs/:id',
    exact: false
  })
  const tidbId = match?.params?.id

  return tidbId
}

export const useCurrentTiDB = (enableQuery = false) => {
  const {
    store: {
      lastVisitLocation: { orgId }
    }
  } = useStores()
  const tidbId = useGetCurrentTidbId()

  return useTiDBServiceGetTidb(
    tidbId || '',
    {
      orgId
    },
    {
      query: {
        enabled: enableQuery,
        select: (data) => getBFFTiDB(data)
      }
    }
  )
}
