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

export async function PUT(
    request: Request,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const currentUser = await getCurrentUser();

        // Ensure user is an employer
        if (!currentUser || currentUser.role !== 'employer') {
            return NextResponse.json({ error: "Unauthorized. Employer access required." }, { status: 401 });
        }

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

        // Verify the job belongs to the current user
        const existingJob = await prisma.job.findUnique({
            where: { id: jobId }
        });

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

        if (existingJob.employer_id !== currentUser.id) {
            return NextResponse.json({ error: "Unauthorized to edit this job" }, { status: 403 });
        }

        // For closed or rejected jobs, prevent editing
        if (existingJob.status === 'closed' || existingJob.status === 'rejected') {
            return NextResponse.json({
                error: `Cannot edit a job with status: ${existingJob.status}. Only active jobs can be edited.`
            }, { status: 400 });
        }

        const body = await request.json();
        const {
            title,
            company,
            description,
            type,
            work_location_type,
            address,
            city,
            state,
            country,
            salary_min,
            salary_max,
            currency,
            experience_level,
            skills // Optional, for simplicity we might not update skills here without complex relation logic, but we can do a set operation.
        } = body;

        if (!title || !description) {
            return NextResponse.json({ error: "Title and description are required." }, { status: 400 });
        }

        // Any edit (draft or changes_requested) should go to pending for admin review
        const newStatus = 'pending';

        const updateData: any = {
            title,
            company,
            description,
            type,
            work_location_type,
            address,
            city,
            state,
            country,
            salary_min: salary_min ? parseInt(salary_min) : null,
            salary_max: salary_max ? parseInt(salary_max) : null,
            currency: currency || "USD",
            experience_level,
            status: newStatus
        };

        const updatedJob = await prisma.$transaction(async (tx) => {
            // Update the core job fields
            const job = await tx.job.update({
                where: { id: jobId },
                data: updateData
            });

            // If skills were provided, we completely replace the old links
            if (skills && Array.isArray(skills)) {
                // Delete existing job_skills
                await tx.jobSkill.deleteMany({
                    where: { job_id: jobId }
                });

                // Connect or create new skills
                for (const skillName of skills) {
                    const skill = await tx.skill.upsert({
                        where: { name: skillName.toLowerCase() },
                        update: {},
                        create: { name: skillName.toLowerCase() }
                    });

                    await tx.jobSkill.create({
                        data: {
                            job_id: jobId,
                            skill_id: skill.id,
                        }
                    });
                }
            }

            return job;
        });

        // Add to audit log
        await prisma.auditLog.create({
            data: {
                user_id: currentUser.id,
                action: "job.edited_by_employer",
                resource_type: "job",
                resource_id: jobId,
                details: {
                    updates: updateData,
                    oldStatus: existingJob.status,
                    newStatus: newStatus
                },
                ip_address: request.headers.get('x-forwarded-for') || 'unknown',
            }
        });

        return NextResponse.json({
            success: true,
            message: newStatus === 'pending' ? "Job updated and resubmitted for review." : "Job updated successfully.",
            job: updatedJob
        });

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