import { NextRequest, NextResponse } from "next/server"; import { db } from "@/lib/db"; import nodemailer from "nodemailer"; // POST /api/admin/notify — send email notification export async function POST(request: NextRequest) { try { // Verify admin token const authHeader = request.headers.get("authorization"); const token = authHeader?.replace("Bearer ", ""); const adminPassword = process.env.ADMIN_PASSWORD || "ml-admin-2024"; if (token !== adminPassword) { return NextResponse.json({ error: "Non autorisé" }, { status: 401 }); } const body = await request.json(); const { action, tpTitle, tpId } = body; // Validate action type if (!["create", "update", "delete"].includes(action)) { return NextResponse.json( { error: "Action invalide. Utilisez create, update ou delete." }, { status: 400 } ); } // Fetch settings const settings = await db.adminSettings.findUnique({ where: { id: "default" }, }); if (!settings?.notifyEmail) { return NextResponse.json({ success: false, message: "Aucune adresse email configurée pour les notifications.", }); } // Check if notification is enabled for this action type if (action === "create" && !settings.notifyOnCreate) { return NextResponse.json({ success: true, message: "Notification désactivée pour la création." }); } if (action === "update" && !settings.notifyOnUpdate) { return NextResponse.json({ success: true, message: "Notification désactivée pour la modification." }); } if (action === "delete" && !settings.notifyOnDelete) { return NextResponse.json({ success: true, message: "Notification désactivée pour la suppression." }); } // Check SMTP configuration if (!settings.smtpHost || !settings.smtpUser || !settings.smtpPass) { return NextResponse.json({ success: false, message: "Configuration SMTP incomplète. Vérifiez les paramètres email.", }); } // Create transporter const transporter = nodemailer.createTransport({ host: settings.smtpHost, port: settings.smtpPort, secure: settings.smtpPort === 465, auth: { user: settings.smtpUser, pass: settings.smtpPass, }, }); const actionLabels: Record = { create: "Nouveau TP ajouté", update: "TP modifié", delete: "TP supprimé", }; const actionIcons: Record = { create: "[+]", update: "[~]", delete: "[-]", }; // Send email await transporter.sendMail({ from: `"IA Academy" <${settings.smtpUser}>`, to: settings.notifyEmail, subject: `[IA Academy] ${actionLabels[action]} : ${tpTitle}`, text: [ `${actionIcons[action]} ${actionLabels[action]}`, "", `Titre : ${tpTitle}`, `ID : ${tpId}`, `Date : ${new Date().toLocaleString("fr-FR", { timeZone: "Europe/Paris" })}`, "", "---", "Ceci est une notification automatique de la plateforme IA Academy.", "Formation IA Machine Learning — 2025/2026", ].join("\n"), html: `

IA Academy

Formation IA Machine Learning

${actionIcons[action]}

${actionLabels[action]}

TITRE DU TP

${tpTitle}

ID ${tpId}
Date ${new Date().toLocaleString("fr-FR", { timeZone: "Europe/Paris" })}

Notification automatique — IA Academy 2025/2026

`, }); return NextResponse.json({ success: true, message: `Notification envoyée à ${settings.notifyEmail}`, }); } catch (error) { console.error("Failed to send notification:", error); return NextResponse.json( { success: false, error: "Erreur lors de l'envoi de la notification. Vérifiez vos paramètres SMTP.", details: error instanceof Error ? error.message : "Erreur inconnue", }, { status: 500 } ); } } // POST /api/admin/notify/test — send a test email export async function PATCH(request: NextRequest) { try { // Verify admin token const authHeader = request.headers.get("authorization"); const token = authHeader?.replace("Bearer ", ""); const adminPassword = process.env.ADMIN_PASSWORD || "ml-admin-2024"; if (token !== adminPassword) { return NextResponse.json({ error: "Non autorisé" }, { status: 401 }); } const body = await request.json(); const { notifyEmail, smtpHost, smtpPort, smtpUser, smtpPass } = body; if (!notifyEmail || !smtpHost || !smtpUser || !smtpPass) { return NextResponse.json( { error: "Tous les champs SMTP sont requis pour le test." }, { status: 400 } ); } const transporter = nodemailer.createTransport({ host: smtpHost, port: Number(smtpPort) || 587, secure: Number(smtpPort) === 465, auth: { user: smtpUser, pass: smtpPass }, }); await transporter.sendMail({ from: `"IA Academy" <${smtpUser}>`, to: notifyEmail, subject: "[IA Academy] Email de test", text: "Ceci est un email de test depuis la plateforme IA Academy. Si vous recevez cet email, la configuration SMTP est correcte.", html: `

Email de test

La configuration SMTP est correcte !

Vous recevrez maintenant les notifications de modification des TPs à cette adresse.

`, }); return NextResponse.json({ success: true, message: `Email de test envoyé à ${notifyEmail}`, }); } catch (error) { console.error("Test email failed:", error); return NextResponse.json( { success: false, error: "Échec de l'envoi du test. Vérifiez vos paramètres SMTP.", details: error instanceof Error ? error.message : "Erreur inconnue", }, { status: 500 } ); } }