import * as FileSystem from 'expo-file-system/legacy';
import * as Sharing from 'expo-sharing';
import type { PdfDownload } from '../api/pdf';

/** Save PDF bytes and open the system share sheet (print / WhatsApp / Files…). */
export async function sharePdfDownload(pdf: PdfDownload): Promise<void> {
  const dir = FileSystem.cacheDirectory ?? FileSystem.documentDirectory;
  if (!dir) throw new Error('Stockage local indisponible.');
  const safeName = (pdf.filename || 'document.pdf').replace(/[^\w.\-]+/g, '_');
  const path = `${dir}${safeName.endsWith('.pdf') ? safeName : `${safeName}.pdf`}`;
  await FileSystem.writeAsStringAsync(path, pdf.base64, {
    encoding: FileSystem.EncodingType.Base64,
  });
  const canShare = await Sharing.isAvailableAsync();
  if (!canShare) {
    throw new Error('Partage non disponible sur cet appareil.');
  }
  await Sharing.shareAsync(path, {
    mimeType: 'application/pdf',
    dialogTitle: pdf.filename,
    UTI: 'com.adobe.pdf',
  });
}
