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

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

        const resolvedParams = await params;
        const jobId = resolvedParams.id;

        const body = await request.json().catch(() => ({}));
        const { featureJob, notifyPremium, addNewsletter, adminNote } = body;

        // Check if job exists and is pending
        const job = await prisma.job.findUnique({
            where: { id: jobId },
            include: { employer: true }
        });

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

        if (job.status !== 'pending' && job.status !== 'draft') {
            return NextResponse.json({ error: "Job is not in a pending state" }, { status: 400 });
        }

        let newInternalNotes = job.internal_notes;
        if (adminNote) {
            const noteToAdd = `\n[${new Date().toISOString()}] Admin Approval Note: ${adminNote}`;
            newInternalNotes = newInternalNotes ? newInternalNotes + noteToAdd : noteToAdd.trim();
        }

        // Update the job to active/published
        const updatedJob = await prisma.job.update({
            where: { id: jobId },
            data: {
                status: 'published',
                posted_at: new Date(), // Reset posted date to now since it's just going live
                is_featured: !!featureJob,
                internal_notes: newInternalNotes
            }
        });

        // Add to audit log
        await prisma.auditLog.create({
            data: {
                user_id: currentUser.id,
                action: "job.approved",
                resource_type: "job",
                resource_id: jobId,
                details: {
                    previous_status: job.status,
                    new_status: 'published',
                    featureJob: !!featureJob,
                    notifyPremium: !!notifyPremium,
                    addNewsletter: !!addNewsletter,
                    adminNote: adminNote || null
                },
                ip_address: request.headers.get('x-forwarded-for') || 'unknown',
            }
        });

        // Fire email notification to employer (non-blocking)
        try {
            if (job.employer?.email) {
                await EmailQueueService.enqueueEmail(
                    'job_approved',
                    job.employer.email,
                    {
                        employerName: job.employer.name || 'Employer',
                        jobTitle: job.title,
                        companyName: job.company,
                        jobId: jobId
                    },
                    job.employer.id
                );
            }
        } catch (emailError) {
            console.error('[Approve] Failed to send approval email:', emailError);
            // Don't fail the request for an email error
        }

        return NextResponse.json({
            success: true,
            message: "Job approved successfully",
            job: updatedJob
        });

    } catch (error: any) {
        console.error("Error approving job:", error);
        return NextResponse.json(
            { error: "Internal server error", details: error.message },
            { status: 500 }
        );
    }
}
