import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { sendChangesRequestedEmail } 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 {
            instructions,
            issues,
            priority,
            reviewProcess
        } = body;

        if (!instructions || typeof instructions !== 'string' || instructions.trim() === '') {
            return NextResponse.json({ error: "Detailed instructions are required." }, { status: 400 });
        }

        // Check if job exists and is pending/draft
        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 });
        }

        // Validate the priority and reviewProcess
        const validPriorities = ['minor', 'moderate', 'critical'];
        const validReviewProcesses = ['auto_apply', 'resubmit'];

        if (priority && !validPriorities.includes(priority)) {
            return NextResponse.json({ error: "Invalid priority level." }, { status: 400 });
        }

        if (reviewProcess && !validReviewProcesses.includes(reviewProcess)) {
            return NextResponse.json({ error: "Invalid review process." }, { status: 400 });
        }

        const newStatus = 'changes_requested';

        // Serialize the change request into a clear markdown string for internal_notes
        // This ensures the admin's changes are visible persistently
        const changeRequestLog = `
=== CHANGE REQUEST: ${new Date().toISOString()} ===
**Admin:** ${currentUser.email}
**Priority:** ${priority?.toUpperCase() || 'MINOR'}
**Review Process:** ${reviewProcess === 'auto_apply' ? 'Auto Apply' : 'Requires Resubmission'}

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

**Instructions to Employer:**
${instructions}
=======================================
`;

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

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

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

        return NextResponse.json({
            success: true,
            message: "Change request successfully submitted",
            job: updatedJob
        });

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