// ============================================================
// src/modules/portail/services/serviceSinistrePortail.ts
// Déclaration de sinistre avec téléversement de pièces
// ============================================================

import axios from 'axios';
import apiClient from '../../../noyau/api/client';
import type { FichierSelectionne } from '../composants/ZoneTeleversementPieces';

// URL de base du micro-service PHP d'upload
// À adapter selon votre configuration (idéalement dans un .env)
const URL_API_UPLOAD =
  import.meta.env.VITE_URL_API_UPLOAD ?? '/api-upload';

interface PayloadDeclaration {
  id_contrat: string;
  date_incident: string;
  description: string;
  lieu_incident?: string;
  montant_estime?: number;
  fichiers?: FichierSelectionne[];
}

interface FichierUploade {
  chemin_fichier: string;
  nom_fichier: string;
  nom_original: string;
  type_mime: string;
  taille_octets: number;
  empreinte_sha256?: string;
  code_type_document: string;
}

export const serviceSinistrePortail = {
  /**
   * Upload un fichier vers le micro-service PHP et retourne les infos
   * à insérer dans stockage.documents.
   */
  async uploadFichier(fichier: File): Promise<FichierUploade> {
    const formData = new FormData();
    formData.append('fichier', fichier);

    const jeton = localStorage.getItem('jeton') ?? '';

    const { data } = await axios.post(
      `${URL_API_UPLOAD}/upload.php?type=sinistre`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${jeton}`,
        },
      }
    );

    return {
      ...data,
      code_type_document: 'declaration_sinistre',
    };
  },

  /**
   * Déclare un sinistre avec pièces jointes :
   *  1. Upload tous les fichiers via le micro-service PHP
   *  2. Appelle la RPC declarer_sinistre_avec_pieces (tout en transaction)
   */
  async declarerAvecPieces(p: PayloadDeclaration): Promise<{
    id: string;
    numero_sinistre: string;
    nb_documents: number;
  }> {
    let documents: FichierUploade[] = [];
    if (p.fichiers && p.fichiers.length > 0) {
      documents = await Promise.all(
        p.fichiers.map((f) => serviceSinistrePortail.uploadFichier(f.fichier))
      );
    }

    const { data } = await apiClient.post('/rpc/declarer_sinistre_avec_pieces', {
      p_id_contrat: p.id_contrat,
      p_date_incident: p.date_incident,
      p_description: p.description,
      p_lieu_incident: p.lieu_incident || null,
      p_montant_estime: p.montant_estime ?? null,
      p_documents: documents,
    });

    return data;
  },

  /**
   * Déclenche le téléchargement d'un document via le micro-service.
   */
  async telechargerDocument(idDocument: string, nomAffichage: string): Promise<void> {
    const jeton = localStorage.getItem('jeton') ?? '';

    const { data } = await axios.get(
      `${URL_API_UPLOAD}/telecharger.php?id=${idDocument}`,
      {
        responseType: 'blob',
        headers: { Authorization: `Bearer ${jeton}` },
      }
    );

    const url = URL.createObjectURL(data);
    const a = document.createElement('a');
    a.href = url;
    a.download = nomAffichage;
    a.click();
    URL.revokeObjectURL(url);
  },

  /**
   * Ouvre l'aperçu d'un document dans un nouvel onglet.
   * Utilise un fetch pour passer le header Authorization, puis un blob URL.
   */
  async ouvrirApercu(idDocument: string): Promise<void> {
    const jeton = localStorage.getItem('jeton') ?? '';

    const { data } = await axios.get(
      `${URL_API_UPLOAD}/apercu.php?id=${idDocument}`,
      {
        responseType: 'blob',
        headers: { Authorization: `Bearer ${jeton}` },
      }
    );

    const url = URL.createObjectURL(data);
    window.open(url, '_blank');
    // Libération mémoire après un court délai (le temps que le navigateur charge)
    setTimeout(() => URL.revokeObjectURL(url), 60_000);
  },
};
