
import { supabase } from "@/integrations/supabase/client";
import { assertDocumentStoragePath, isManagedDocumentStoragePath, type DocumentUploadPlan } from "@/services/documentGuards";

export function useSupabaseStorage() {
  const uploadDocument = async (tripId: string, file: File, plan: DocumentUploadPlan) => {
    try {
      assertDocumentStoragePath(tripId, plan.storagePath);

      // Add a timeout to prevent hanging uploads
      const uploadPromise = supabase.storage
        .from('documents')
        .upload(plan.storagePath, file, {
          cacheControl: '3600',
          contentType: plan.mimeType,
          upsert: false,
        });

      const timeoutPromise = new Promise<never>((_, reject) =>
        setTimeout(() => reject(new Error("Le téléchargement a pris trop de temps")), 30000)
      );

      // Race between upload and timeout
      const result = await Promise.race([
        uploadPromise,
        timeoutPromise
      ]);

      // Properly type check the result
      if (result.error) throw result.error;

      return plan.storagePath;
    } catch (error) {
      console.error('Error uploading document:', error);
      throw error;
    }
  };

  const uploadBannerImage = async (file: File) => {
    try {
      const fileExt = file.name.split('.').pop();
      const filePath = `${Math.random().toString(36).substring(2)}.${fileExt}`;

      // Upload the file to the trip_banners bucket
      const { error } = await supabase.storage
        .from('trip_banners')
        .upload(filePath, file);

      if (error) throw error;

      // Get the public URL of the uploaded file
      const { data: { publicUrl } } = supabase.storage
        .from('trip_banners')
        .getPublicUrl(filePath);

      return publicUrl;
    } catch (error) {
      console.error('Error uploading banner image:', error);
      throw error;
    }
  };

  const getDocumentDownloadUrl = async (tripId: string, documentId: string) => {
    try {
      const { data: document, error: accessError } = await supabase
        .from('documents')
        .select('id, url')
        .eq('id', documentId)
        .eq('trip_id', tripId)
        .single();
      if (accessError || !document) throw accessError || new Error('Document inaccessible');
      if (!isManagedDocumentStoragePath(tripId, document.url)) throw new Error('Chemin de document invalide');
      const { data, error } = await supabase.storage.from('documents').createSignedUrl(document.url, 60);
      if (error) throw error;
      return data.signedUrl;
    } catch (error) {
      console.error('Document access denied:', error);
      throw error;
    }
  };

  const deleteStorageDocument = async (tripId: string, filePath: string) => {
    try {
      if (!isManagedDocumentStoragePath(tripId, filePath)) throw new Error('Chemin de document invalide');
      const { error } = await supabase.storage
        .from('documents')
        .remove([filePath]);

      if (error) throw error;
      return true;
    } catch (error) {
      console.error('Error deleting document:', error);
      throw error;
    }
  };

  return {
    uploadDocument,
    uploadBannerImage,
    getDocumentDownloadUrl,
    deleteStorageDocument
  };
}
