"use client"

import { useMutation, useQueryClient } from "@tanstack/react-query"
import { apiClient } from "@/lib/api/client"
import type { ApiOrgSettingsResponse } from "@/lib/api/admin-org-types"
import { ORG_SETTINGS_QUERY_KEY } from "@/lib/api/hooks/use-org-settings"

export function useTestIdentityProvider() {
  return useMutation({
    mutationFn: (providerID: string) =>
      apiClient.post<{ ok: boolean }>(
        `/admin/org/identity-providers/${encodeURIComponent(providerID)}/test`
      ),
  })
}

export function useSyncIdentityProvider() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (providerID: string) =>
      apiClient.post<ApiOrgSettingsResponse>(
        `/admin/org/identity-providers/${encodeURIComponent(providerID)}/sync`
      ),
    onSuccess: (data) => {
      queryClient.setQueryData(ORG_SETTINGS_QUERY_KEY, data)
    },
  })
}

export function useIdentityProviderRedirectURI() {
  return useMutation({
    mutationFn: (slug: string) =>
      apiClient.get<{ slug: string; redirect_uri: string }>(
        `/admin/org/identity-providers/redirect-uri/${encodeURIComponent(slug)}`
      ),
  })
}
