import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser || currentUser.role !== 'admin') {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const resolvedParams = await params;
        const email = await prisma.emailQueue.findUnique({ where: { id: resolvedParams.id } });

        if (!email) {
            return NextResponse.json({ error: "Email not found" }, { status: 404 });
        }

        if (email.status === 'SENT') {
            return NextResponse.json({ error: "Email already sent" }, { status: 400 });
        }

        // Reset the email for processing
        await prisma.emailQueue.update({
            where: { id: resolvedParams.id },
            data: {
                status: 'PENDING',
                attempts: 0,
                last_error: null
            }
        });

        return NextResponse.json({ success: true, message: "Email queued for retry" });
    } catch (error: any) {
        console.error("Error retrying email:", error);
        return NextResponse.json({ error: "Internal server error" }, { status: 500 });
    }
}
