import { useState } from 'react';
import { toast } from 'sonner';
import { api } from '@/api/client';

export function useArtifactDownload(chatId: string, messageId: string, format: 'md' | 'html') {
  const [downloading, setDownloading] = useState(false);

  async function download() {
    if (downloading) return;
    setDownloading(true);
    try {
      const { url, path } = await api.messages.downloadArtifact(chatId, messageId, format);
      const a = document.createElement('a');
      a.href = url;
      a.rel = 'noopener';
      a.click();
      toast.success(`Saved to ${path}`);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'download failed');
    } finally {
      setDownloading(false);
    }
  }

  return { downloading, download };
}
