File size: 12,705 Bytes
4bea261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import { txasupabase } from '../../../lib/txasupabase.js';

// 1. TẢI DANH SÁCH BÌNH LUẬN + DANH SÁCH BỊ CHẶN
export async function GET({ request, cookies }) {
  const url = new URL(request.url);
  const slug = url.searchParams.get('slug');

  const token = cookies.get('auth_token')?.value;
  let user = null;
  if (token) {
    try {
      user = JSON.parse(Buffer.from(token, 'base64').toString('utf-8'));
    } catch (e) {}
  }

  if (slug === 'all') {
    if (!user || user.role !== 'admin') {
      return new Response(JSON.stringify({ error: 'Bạn không có quyền truy cập dữ liệu này!' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }
  } else if (!slug) {
    return new Response(JSON.stringify({ error: 'Thiếu slug phim!' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' }
    });
  }

  try {
    let query = txasupabase.supabase
      .from('comments')
      .select('*')
      .order('created_at', { ascending: false });

    if (slug !== 'all') {
      query = query.eq('movie_slug', slug);
    }

    const { data: comments, error } = await query;

    if (error) throw error;

    const bannedUsers = await txasupabase.getSetting('banned_commenters') || [];

    // Nạp thông tin hồ sơ người dùng (profile) phục vụ cho popup khi hover
    const usernames = comments ? [...new Set(comments.map(c => c.username).filter(Boolean))] : [];
    const userProfiles = {};

    if (usernames.length > 0) {
      // 1. Tải danh sách user (tỉnh, xã, phim yêu thích, avatar_url)
      const { data: users } = await txasupabase.supabase
        .from('users')
        .select('username, province, ward, favorites, avatar_url')
        .in('username', usernames);

      // 2. Tải số lượng bình luận của các user này trên toàn hệ thống
      const { data: allUserComments } = await txasupabase.supabase
        .from('comments')
        .select('username')
        .in('username', usernames);

      const userCommentsCounts = {};
      if (allUserComments) {
        allUserComments.forEach(item => {
          userCommentsCounts[item.username] = (userCommentsCounts[item.username] || 0) + 1;
        });
      }

      if (users) {
        users.forEach(u => {
          userProfiles[u.username] = {
            username: u.username,
            province: u.province || '',
            ward: u.ward || '',
            avatar_url: u.avatar_url || '',
            likesCount: Array.isArray(u.favorites) ? u.favorites.length : 0,
            commentsCount: userCommentsCounts[u.username] || 0
          };
        });
      }
    }

    // Nếu tải cho admin, lấy thêm tên các phim để map hiển thị
    let movieMap = {};
    if (slug === 'all') {
      const { data: dbMovies } = await txasupabase.supabase
        .from('movies')
        .select('slug, movie');
      if (dbMovies) {
        dbMovies.forEach(m => {
          movieMap[m.slug] = m.movie?.name || m.slug;
        });
      }
    }

    return new Response(JSON.stringify({ 
      comments: comments || [], 
      bannedUsers,
      userProfiles,
      movieMap
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: 'Lỗi tải bình luận: ' + error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

// 2. GỬI BÌNH LUẬN MỚI
export async function POST({ request, cookies }) {
  // Kiểm tra đăng nhập
  const token = cookies.get('auth_token')?.value;
  let user = null;
  if (token) {
    try {
      user = JSON.parse(Buffer.from(token, 'base64').toString('utf-8'));
    } catch (e) {}
  }

  if (!user) {
    return new Response(JSON.stringify({ error: 'Vui lòng đăng nhập trước khi bình luận!' }), {
      status: 401,
      headers: { 'Content-Type': 'application/json' }
    });
  }

  try {
    // Kiểm tra xem người dùng có bị Admin chặn bình luận không
    const bannedUsers = await txasupabase.getSetting('banned_commenters') || [];
    if (Array.isArray(bannedUsers) && bannedUsers.includes(user.username)) {
      return new Response(
        JSON.stringify({ error: 'Tài khoản của bạn đã bị quản trị viên chặn bình luận trên hệ thống!' }), 
        { status: 403, headers: { 'Content-Type': 'application/json' } }
      );
    }

    const { movieSlug, content, isSpoiler, episodeName, serverName, movieType } = await request.json();

    if (!movieSlug || !content) {
      return new Response(JSON.stringify({ error: 'Thiếu thông tin bình luận!' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Tự động làm sạch & chuẩn hóa tên tập phim trước khi lưu
    let finalEpisodeName = null;
    if (episodeName) {
      const isSingle = movieType === 'single' || movieType === 'movie';
      if (isSingle) {
        finalEpisodeName = 'Full';
      } else {
        const numMatch = String(episodeName).match(/\d+/);
        if (numMatch) {
          const num = parseInt(numMatch[0], 10);
          finalEpisodeName = `Tập ${num}`;
        } else {
          let cleaned = String(episodeName).trim().replace(/^tập\s*/i, '');
          finalEpisodeName = `Tập ${cleaned}`;
        }
      }
    }

    const { data, error } = await txasupabase.supabase
      .from('comments')
      .insert({
        movie_slug: movieSlug,
        username: user.username,
        content: content.trim(),
        is_spoiler: !!isSpoiler,
        episode_name: finalEpisodeName,
        server_name: serverName || null,
        likes: [],
        dislikes: []
      })
      .select();

    if (error) throw error;

    return new Response(JSON.stringify({ message: 'Gửi bình luận thành công!', data: data?.[0] }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: 'Lỗi gửi bình luận: ' + error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

// 3. TƯƠNG TÁC THÍCH / GHÉT & CẤM BÌNH LUẬN
export async function PUT({ request, cookies }) {
  const token = cookies.get('auth_token')?.value;
  let user = null;
  if (token) {
    try {
      user = JSON.parse(Buffer.from(token, 'base64').toString('utf-8'));
    } catch (e) {}
  }

  if (!user) {
    return new Response(JSON.stringify({ error: 'Vui lòng đăng nhập!' }), {
      status: 401,
      headers: { 'Content-Type': 'application/json' }
    });
  }

  try {
    const body = await request.json();
    const { commentId, action } = body;

    if (!action) {
      return new Response(JSON.stringify({ error: 'Thiếu hành động tương tác!' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // A. XỬ LÝ ADMIN CẤM / MỞ CHẶN NGƯỜI DÙNG
    if (action === 'ban' || action === 'unban') {
      if (user.role !== 'admin') {
        return new Response(JSON.stringify({ error: 'Bạn không có quyền quản trị để thực hiện!' }), {
          status: 403,
          headers: { 'Content-Type': 'application/json' }
        });
      }

      const { targetUsername } = body;
      if (!targetUsername) {
        return new Response(JSON.stringify({ error: 'Thiếu tên tài khoản cần xử lý!' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
      }

      let bannedUsers = await txasupabase.getSetting('banned_commenters') || [];
      if (!Array.isArray(bannedUsers)) bannedUsers = [];

      if (action === 'ban') {
        if (!bannedUsers.includes(targetUsername)) {
          bannedUsers.push(targetUsername);
        }
      } else {
        bannedUsers = bannedUsers.filter(u => u !== targetUsername);
      }

      await txasupabase.saveSetting('banned_commenters', bannedUsers);

      return new Response(JSON.stringify({
        message: action === 'ban' ? `Đã chặn bình luận của @${targetUsername} thành công!` : `Đã mở chặn bình luận cho @${targetUsername}!`,
        bannedUsers
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // B. XỬ LÝ THÍCH / GHÉT BÌNH LUẬN
    if (!commentId || !['like', 'dislike'].includes(action)) {
      return new Response(JSON.stringify({ error: 'Hành động không hợp lệ!' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const { data: comment, error: fetchError } = await txasupabase.supabase
      .from('comments')
      .select('*')
      .eq('id', commentId)
      .maybeSingle();

    if (fetchError || !comment) {
      return new Response(JSON.stringify({ error: 'Bình luận không tồn tại!' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    let likes = comment.likes || [];
    let dislikes = comment.dislikes || [];
    const username = user.username;

    if (action === 'like') {
      if (likes.includes(username)) {
        // Tắt like
        likes = likes.filter(u => u !== username);
      } else {
        // Bật like, tắt dislike
        likes.push(username);
        dislikes = dislikes.filter(u => u !== username);
      }
    } else if (action === 'dislike') {
      if (dislikes.includes(username)) {
        // Tắt dislike
        dislikes = dislikes.filter(u => u !== username);
      } else {
        // Bật dislike, tắt like
        dislikes.push(username);
        likes = likes.filter(u => u !== username);
      }
    }

    const { data: updatedComment, error: updateError } = await txasupabase.supabase
      .from('comments')
      .update({ likes, dislikes })
      .eq('id', commentId)
      .select()
      .single();

    if (updateError) throw updateError;

    return new Response(JSON.stringify({
      message: 'Tương tác thành công!',
      likesCount: updatedComment.likes?.length || 0,
      dislikesCount: updatedComment.dislikes?.length || 0,
      likes: updatedComment.likes || [],
      dislikes: updatedComment.dislikes || []
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: 'Lỗi xử lý tương tác: ' + error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

// 4. XÓA BÌNH LUẬN
export async function DELETE({ request, cookies }) {
  const token = cookies.get('auth_token')?.value;
  let user = null;
  if (token) {
    try {
      user = JSON.parse(Buffer.from(token, 'base64').toString('utf-8'));
    } catch (e) {}
  }

  if (!user) {
    return new Response(JSON.stringify({ error: 'Vui lòng đăng nhập!' }), {
      status: 401,
      headers: { 'Content-Type': 'application/json' }
    });
  }

  try {
    const { commentId } = await request.json();

    if (!commentId) {
      return new Response(JSON.stringify({ error: 'Thiếu ID bình luận cần xóa!' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Lấy thông tin bình luận
    const { data: comment, error: fetchError } = await txasupabase.supabase
      .from('comments')
      .select('*')
      .eq('id', commentId)
      .maybeSingle();

    if (fetchError || !comment) {
      return new Response(JSON.stringify({ error: 'Bình luận không tồn tại!' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Kiểm tra quyền xóa: Phải là chủ nhân bình luận hoặc là Admin
    if (comment.username !== user.username && user.role !== 'admin') {
      return new Response(JSON.stringify({ error: 'Bạn không có quyền xóa bình luận này!' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const { error: deleteError = null } = await txasupabase.supabase
      .from('comments')
      .delete()
      .eq('id', commentId);

    if (deleteError) throw deleteError;

    return new Response(JSON.stringify({ message: 'Xóa bình luận thành công!' }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: 'Lỗi xóa bình luận: ' + error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}