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

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

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

        const body = await request.json();
        const {
            primaryCategory,
            primaryReason,
            detailedExplanation,
            issues,
            severity,
            resubmitWhen,
            resubmitPriority,
            adminNotes,
            tags
        } = body;

        if (!primaryCategory || !primaryReason || !detailedExplanation) {
            return NextResponse.json({ error: "Primary category, reason, and detailed explanation are required" }, { status: 400 });
        }

        // 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 });
        }

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

        // Update the job based on severity
        // Note: Our Prisma schema currently only has generic statuses like 'rejected', 'pending', etc.
        // We will map 'hard' to 'rejected' for now, but in the future could map to 'banned'
        const newStatus = 'rejected';

        // Serialize the 8-step data into a clear markdown string for internal_notes
        const rejectionReport = `
=== REJECTION REPORT: ${new Date().toISOString()} ===
**Admin:** ${currentUser.email}
**Category:** ${primaryCategory}
**Reason:** ${primaryReason}
**Severity:** ${severity.toUpperCase()}
**Resubmit:** ${resubmitWhen} (Priority: ${resubmitPriority})

**Tags:** ${tags || 'None'}
**Admin Notes:** ${adminNotes || 'None'}

**Issues Detected:**
${Object.entries(issues || {}).filter(([_, checked]) => checked).map(([key]) => `- ${key}`).join('\n') || 'None additional'}

**Explanation to Employer:**
${detailedExplanation}
=======================================
`;

        const updatedJob = await prisma.job.update({
            where: { id: jobId },
            data: {
                status: newStatus,
                internal_notes: job.internal_notes ? `${job.internal_notes}\n\n${rejectionReport}` : rejectionReport
            }
        });

        // Add to audit log with the full JSON payload
        await prisma.auditLog.create({
            data: {
                user_id: currentUser.id,
                action: "job.rejected_advanced",
                resource_type: "job",
                resource_id: jobId,
                details: body, // Store the exact JSON for future analytics
                ip_address: request.headers.get('x-forwarded-for') || 'unknown',
            }
        });

        // Fire email notification to employer (non-blocking)
        try {
            if (job.employer?.email) {
                await sendRejectionEmail(
                    job.employer.email,
                    job.employer.name || 'Employer',
                    { id: jobId, title: job.title, company: job.company },
                    primaryReason,
                    detailedExplanation
                );
            }
        } catch (emailError) {
            console.error('[Reject] Failed to send rejection email:', emailError);
        }

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

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