import { useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { buildSecureStorageKey } from '@/lib/secureStorageNaming';

export function useFileUpload() {
  const [uploading, setUploading] = useState(false);
  const { toast } = useToast();

  const uploadFiles = async (files, bucket = 'documents', folder = 'uploads') => {
    if (!files || files.length === 0) return [];

    setUploading(true);
    const uploadedFiles = [];
    const errors = [];

    try {
      for (const file of files) {
        if (file.size > 25 * 1024 * 1024) {
          errors.push(`${file.name} exceeds 25MB limit.`);
          continue;
        }

        // Randomized + sanitized storage key — the original filename is
        // returned in the result (`name`) so callers can store it for display.
        const fileName = buildSecureStorageKey(file.name, folder);

        const { data, error: uploadError } = await supabase.storage
          .from(bucket)
          .upload(fileName, file);

        if (uploadError) {
          console.error(`Error uploading ${file.name}:`, uploadError);
          errors.push(`Failed to upload ${file.name}`);
          continue;
        }

        const { data: publicUrlData } = supabase.storage
          .from(bucket)
          .getPublicUrl(fileName);

        uploadedFiles.push({
          name: file.name,
          path: fileName,
          url: publicUrlData.publicUrl,
          size: file.size,
          type: file.type,
          uploaded_at: new Date().toISOString()
        });
      }

      if (errors.length > 0) {
        toast({ variant: "destructive", title: "Upload Issues", description: `Some files failed: ${errors.join(', ')}` });
      }

      return uploadedFiles;
    } catch (error) {
      console.error('Critical upload error:', error);
      toast({ variant: "destructive", title: "Upload Failed", description: error.message || "An unexpected error occurred." });
      return [];
    } finally {
      setUploading(false);
    }
  };

  return { uploadFiles, uploading };
}
