"use client"

import { useCallback } from "react"
import type { OrgPolicySectionKey } from "@/lib/api/admin-org-types"
import { useUpdateOrgSettings } from "@/lib/api/hooks/use-org-settings"
import { pickApiOrgPolicySections, storeToApiOrgPolicy } from "@/lib/admin-settings/map-api-org-settings"
import { useOrgSettingsStore } from "@/lib/admin-settings/org-settings-store"

export function useSaveOrgPolicy() {
  const update = useUpdateOrgSettings()

  return useCallback(
    async (sections?: OrgPolicySectionKey[]) => {
      const state = useOrgSettingsStore.getState()
      const policy = sections?.length
        ? pickApiOrgPolicySections(state, sections)
        : storeToApiOrgPolicy(state)
      await update.mutateAsync({ policy })
    },
    [update]
  )
}
