import { txasupabase } from '../../lib/txasupabase.js'; export const POST = async ({ request }) => { try { const body = await request.json(); const { movie_slug, movie_name, episode_name, error_type, description } = body; if (!error_type) { return new Response(JSON.stringify({ error: 'Vui lòng chọn loại lỗi!' }), { status: 400, headers: { 'Content-Type': 'application/json' } }); } // 1. Lưu báo cáo lỗi vào cơ sở dữ liệu const report = await txasupabase.createReport( movie_slug || '', movie_name || '', episode_name || '', error_type, description || '' ); // 2. Ghi lại log hoạt động await txasupabase.createLog( 'bug_report', 'warn', `Báo cáo lỗi phim "${movie_name || 'Không rõ'}" (${episode_name || 'Không rõ'}): ${error_type}`, { movie_slug, movie_name, episode_name, error_type, description } ); // 3. Gửi email thông báo cho Admin try { const settings = await txasupabase.getSettings(); // Tìm email Admin nhận thông báo let adminEmail = settings.admin_email || settings.smtp_user; if (!adminEmail) { const { data: adminUsers } = await txasupabase.supabase .from('users') .select('email') .eq('role', 'admin') .limit(1); if (adminUsers && adminUsers.length > 0) { adminEmail = adminUsers[0].email; } } if (adminEmail && settings.smtp_user && settings.smtp_pass) { const siteUrl = settings.site_url || 'http://localhost:4321'; const adminUrl = `${siteUrl}/admin/bao-cao-loi`; // URL trang quản lý lỗi của admin await txasupabase.sendMail({ to: adminEmail, subject: `[TPHIMX - BÁO CÁO LỖI PHIM]: Phim "${movie_name || 'Không rõ'}" bị lỗi ${error_type}`, templateName: 'bug_report', placeholders: { movie_name: movie_name || 'Không rõ', episode_name: episode_name || 'Không rõ', error_type, description: description || 'Người dùng không để lại mô tả bổ sung.', admin_url: adminUrl } }); } else { console.log('[Report API]: SMTP not configured or Admin email missing, skipped email notification.'); } } catch (mailErr) { console.error('[Report Mail Error]:', mailErr); await txasupabase.createLog( 'bug_report_mail_failed', 'warn', `Lỗi gửi mail báo cáo lỗi cho phim "${movie_name || 'Không rõ'}": ${mailErr.message}` ); } return new Response(JSON.stringify({ success: true, message: 'Cảm ơn bạn đã báo cáo lỗi! Admin sẽ kiểm tra và khắc phục sớm nhất.', data: report }), { status: 200, headers: { 'Content-Type': 'application/json' } }); } catch (err) { console.error('Error handling report API:', err); return new Response(JSON.stringify({ error: 'Có lỗi xảy ra trên hệ thống!' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } };