"use client"

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { apiClient } from "@/lib/api/client"
import type {
  ApiOrgSettingsPutRequest,
  ApiOrgSettingsResponse,
} from "@/lib/api/admin-org-types"
import { useAuthReady } from "@/lib/api/use-auth-ready"
import { usePlatformAdminAccess } from "@/lib/auth/use-platform-admin-access"

export const ORG_SETTINGS_QUERY_KEY = ["admin", "org-settings"] as const

export function useOrgSettings() {
  const { ready, authenticated } = useAuthReady()
  const { isAdmin, adminReady } = usePlatformAdminAccess()

  return useQuery({
    queryKey: ORG_SETTINGS_QUERY_KEY,
    queryFn: () => apiClient.get<ApiOrgSettingsResponse>("/admin/org/settings"),
    staleTime: 60_000,
    enabled: ready && authenticated && adminReady && isAdmin,
    retry: 1,
  })
}

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

  return useMutation({
    mutationFn: (body: ApiOrgSettingsPutRequest) =>
      apiClient.put<ApiOrgSettingsResponse>("/admin/org/settings", body),
    onSuccess: (data) => {
      queryClient.setQueryData(ORG_SETTINGS_QUERY_KEY, data)
    },
  })
}
