File size: 2,296 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
import { txasupabase } from '../../../lib/txasupabase.js';

export const GET = async ({ cookies }) => {
  try {
    // 1. Kiểm tra quyền Admin bảo mật
    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 || user.role !== 'admin') {
      return new Response(JSON.stringify({ error: 'Bạn không có quyền quản trị!' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // 2. Lấy số lượng Zalo Access đang chờ duyệt
    const { count: pendingZalo, error: zaloErr } = await txasupabase.supabase
      .from('zalo_access')
      .select('*', { count: 'exact', head: true })
      .eq('status', 'pending');

    if (zaloErr) throw zaloErr;

    // 3. Lấy số lượng Báo cáo lỗi đang chờ xử lý
    const { count: pendingReports, error: reportErr } = await txasupabase.supabase
      .from('reports')
      .select('*', { count: 'exact', head: true })
      .eq('status', 'pending');

    if (reportErr) throw reportErr;

    // 4. Lấy số lượng bình luận và thông tin bình luận mới nhất
    const { data: commentsData, error: commentErr } = await txasupabase.supabase
      .from('comments')
      .select('id, created_at')
      .order('created_at', { ascending: false });

    if (commentErr) throw commentErr;

    const totalComments = commentsData ? commentsData.length : 0;
    const latestCommentTime = commentsData && commentsData.length > 0 ? commentsData[0].created_at : null;

    return new Response(JSON.stringify({
      success: true,
      pendingZalo: pendingZalo || 0,
      pendingReports: pendingReports || 0,
      totalComments,
      latestCommentTime,
      comments: commentsData || []
    }), {
      status: 200,
      headers: { 
        'Content-Type': 'application/json',
        'Cache-Control': 'no-store, max-age=0'
      }
    });

  } catch (err) {
    console.error('Error in admin notifications API:', err);
    return new Response(JSON.stringify({ error: err.message || 'Lỗi hệ thống!' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};