import {type ActionsResult, type ReleaseAction} from '@sanity/sdk'

import {type ResourceHandle} from '../../config/handles'
import {useApplyActions} from '../helpers/useApplyActions'

/**
 * @public
 */
interface UseApplyReleaseActions {
  (): (action: ReleaseAction | ReleaseAction[], options?: ResourceHandle) => Promise<ActionsResult>
}

/**
 * @public
 *
 * Provides a stable callback function for applying one or more release actions.
 *
 * This hook wraps the core `applyDocumentActions` functionality from `@sanity/sdk`,
 * integrating it with the React component lifecycle and {@link SanityInstance}.
 * It accepts release-lifecycle actions generated by {@link createRelease},
 * {@link editRelease}, {@link publishRelease}, {@link scheduleRelease},
 * {@link unscheduleRelease}, {@link archiveRelease}, {@link unarchiveRelease},
 * and {@link deleteRelease}.
 *
 * Note that actions submitted via this hook will cascade to the documents in the release.
 * For example, if you create a release and then publish it, the documents in the release will be published.
 * If you delete a published release, the version documents will be deleted.
 *
 * Features:
 * - Applies one or multiple `ReleaseAction` objects.
 * - Supports optimistic updates for create/edit/delete: local release state
 *   reflects changes immediately while in-flight.
 * - Handles batching: multiple actions passed together are submitted as a
 *   single atomic transaction.
 *
 * Release actions cannot be combined with `liveEdit` document actions in the
 * same transaction. Submit them as separate transactions if you need both.
 *
 * @category Releases
 * @returns A stable callback. When called with a single `ReleaseAction` or an
 * array of `ReleaseAction`s, it returns a promise that resolves to an
 * {@link ActionsResult}.
 *
 * @example Create and schedule a release
 * ```tsx
 * import {
 *   createRelease,
 *   scheduleRelease,
 *   useApplyReleaseActions,
 *   type ReleaseHandle,
 * } from '@sanity/sdk-react'
 *
 * function ScheduleReleaseButton({release}: {release: ReleaseHandle}) {
 *   const applyRelease = useApplyReleaseActions()
 *
 *   const handleSchedule = () =>
 *     applyRelease([
 *       createRelease(release, {title: 'Summer drop', releaseType: 'asap'}),
 *       scheduleRelease(release, '2026-06-01T00:00:00Z'),
 *     ])
 *
 *   return <button onClick={handleSchedule}>Schedule</button>
 * }
 * ```
 *
 * @example Publish a release
 * ```tsx
 * import {publishRelease, useApplyReleaseActions} from '@sanity/sdk-react'
 *
 * function PublishButton({releaseId}: {releaseId: string}) {
 *   const applyRelease = useApplyReleaseActions()
 *   return (
 *     <button onClick={() => applyRelease(publishRelease({releaseId}))}>
 *       Publish all documents in the release
 *     </button>
 *   )
 * }
 * ```
 */
export const useApplyReleaseActions: UseApplyReleaseActions = () => {
  return useApplyActions() as ReturnType<UseApplyReleaseActions>
}
