File size: 5,010 Bytes
6711fd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';

interface UploadProgress {
  loaded: number;
  total: number;
  percentage: number;
}

interface UploadResult {
  url: string;
  path: string;
  size: number;
}

interface ModUploadData {
  title: string;
  description: string;
  category: string;
  platform: 'java' | 'bedrock' | 'both';
  minecraft_version: string;
  mod_version: string;
  tags: string[];
  file: File;
  thumbnail?: File;
  screenshots?: File[];
}

export const useFileUpload = () => {
  const { user } = useAuth();
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState<UploadProgress>({ loaded: 0, total: 0, percentage: 0 });

  const getFileType = (file: File): string => {
    const extension = file.name.split('.').pop()?.toLowerCase() || '';
    const typeMap: Record<string, string> = {
      'jar': 'jar',
      'zip': 'zip',
      'mcaddon': 'mcaddon',
      'mcpack': 'mcpack',
      'mcworld': 'mcworld',
      'mctemplate': 'mctemplate',
    };
    return typeMap[extension] || 'zip';
  };

  const uploadFile = async (
    file: File,
    bucket: string,
    _folder: string
  ): Promise<UploadResult> => {
    if (!user) throw new Error('يجب تسجيل الدخول أولاً');

    const fileExt = file.name.split('.').pop();
    const uniqueId = typeof crypto.randomUUID === 'function'
      ? crypto.randomUUID()
      : Math.random().toString(36).substring(2) + Date.now().toString(36);
    const fileName = `${user.id}/${Date.now()}-${uniqueId}.${fileExt}`;

    const { data, error } = await supabase.storage
      .from(bucket)
      .upload(fileName, file, {
        cacheControl: '3600',
        upsert: false,
      });

    if (error) throw error;

    const { data: urlData } = supabase.storage
      .from(bucket)
      .getPublicUrl(data.path);

    return {
      url: urlData.publicUrl,
      path: data.path,
      size: file.size,
    };
  };

  const uploadMod = async (modData: ModUploadData): Promise<string> => {
    if (!user) {
      toast.error('يجب تسجيل الدخول لرفع الإضافات');
      throw new Error('Not authenticated');
    }

    setUploading(true);
    setProgress({ loaded: 0, total: 100, percentage: 0 });

    try {
      toast.loading('جاري رفع الملف...', { id: 'upload' });
      setProgress({ loaded: 20, total: 100, percentage: 20 });

      const modFile = await uploadFile(modData.file, 'mods', user.id);

      let thumbnailUrl = null;
      if (modData.thumbnail) {
        setProgress({ loaded: 40, total: 100, percentage: 40 });
        const thumbnail = await uploadFile(modData.thumbnail, 'thumbnails', user.id);
        thumbnailUrl = thumbnail.url;
      }

      const screenshotUrls: string[] = [];
      if (modData.screenshots && modData.screenshots.length > 0) {
        setProgress({ loaded: 60, total: 100, percentage: 60 });
        for (const screenshot of modData.screenshots) {
          const uploaded = await uploadFile(screenshot, 'screenshots', user.id);
          screenshotUrls.push(uploaded.url);
        }
      }

      setProgress({ loaded: 80, total: 100, percentage: 80 });

      const { data: mod, error } = await supabase
        .from('mods')
        .insert({
          user_id: user.id,
          title: modData.title,
          description: modData.description,
          category: modData.category,
          platform: modData.platform,
          minecraft_version: modData.minecraft_version,
          mod_version: modData.mod_version,
          tags: modData.tags,
          file_url: modFile.url,
          file_type: getFileType(modData.file),
          file_size: modFile.size,
          thumbnail_url: thumbnailUrl,
          screenshots: screenshotUrls,
          is_approved: false,
        })
        .select('id')
        .single();

      if (error) throw error;

      const { count: modsCount } = await supabase
        .from('mods')
        .select('id', { count: 'exact', head: true })
        .eq('user_id', user.id);

      if (modsCount !== null) {
        await supabase
          .from('profiles')
          .update({ total_uploads: modsCount })
          .eq('user_id', user.id);
      }

      setProgress({ loaded: 100, total: 100, percentage: 100 });
      toast.success('تم رفع الإضافة بنجاح! 🎉', { id: 'upload' });

      return mod.id;
    } catch (error: any) {
      console.error('Upload error:', error);
      toast.error(error.message || 'فشل في رفع الإضافة', { id: 'upload' });
      throw error;
    } finally {
      setUploading(false);
    }
  };

  const deleteFile = async (bucket: string, path: string) => {
    const { error } = await supabase.storage.from(bucket).remove([path]);
    if (error) throw error;
  };

  return {
    uploadMod,
    uploadFile,
    deleteFile,
    uploading,
    progress,
  };
};