import { NextResponse } from "next/server";
import { db } from "@/app/lib/db";
import { transporter, baseMail } from "@/app/lib/mailer";

export async function POST(req) {
    const { id } = await req.json();

    if (!id) {
        return NextResponse.json({ message: 'Invalid ID' }, { status: 400 });
    }

    (await db).query('UPDATE users SET ENABLED = ? WHERE USER_ID = ?', ['True', id]);

    const [rows] = await (await db).query('SELECT EMAIL FROM users WHERE USER_ID = ?', [id]);

    console.log(rows);

    const mailOptions = {
        from: '"InfoGare" <contact@infogare.fr>',
        to: rows[0].EMAIL,
        replyTo: 'contact@infogare.fr',
        subject: 'Activation de votre compte InfoGare',
        html: baseMail('Activation de votre compte InfoGare', `
            <p>Bonjour, </p>
            <p>Votre compte InfoGare a été activé par un administrateur. </p>
            <p><b>L'équipe InfoGare</b></p>
        `),
    };

    const res = await transporter.sendMail(mailOptions);

    if (res.accepted.length === 0) {
        return NextResponse.json({ message: 'Invalid email' }, { status: 400 });
    } else {
        return NextResponse.json({ message: 'OK' });
    }
}