import { toValue, type MaybeRefOrGetter } from 'vue'
import { toast } from 'vue-sonner'
import { useSemanticModelsStore } from '@/stores/semantic-models'

interface UseSaveDiscardOptions {
  modelId: MaybeRefOrGetter<string>
  versionId: MaybeRefOrGetter<string>
  onDiscard?: () => void | Promise<void>
}

export function useSaveDiscard(options: UseSaveDiscardOptions) {
  const store = useSemanticModelsStore()

  async function handleSave() {
    const currentModelId = toValue(options.modelId)
    const currentVersionId = toValue(options.versionId)
    if (!currentModelId || !currentVersionId) return

    try {
      await store.saveDraft(currentModelId, currentVersionId)
      toast.success('Version saved')
    } catch (error) {
      toast.error('Failed to save', {
        description: error instanceof Error ? error.message : 'Unknown error',
      })
    }
  }

  async function handleDiscard() {
    store.discardDraft()
    if (!options.onDiscard) return

    try {
      await options.onDiscard()
    } catch (error) {
      toast.error('Failed to apply post-discard updates', {
        description: error instanceof Error ? error.message : 'Unknown error',
      })
    }
  }

  return {
    handleSave,
    handleDiscard,
  }
}
