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

// Valid status transitions for employers
// Only admin-approved (published) jobs can have their status changed by employers
const VALID_TRANSITIONS: Record<string, string[]> = {
    published: ["suspended", "closed"],
    suspended: ["published", "closed"],
    closed: [], // closed is final for employers
};

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

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

        const { id: jobId } = await params;
        const body = await request.json();
        const { status } = body;

        if (!status) {
            return NextResponse.json(
                { error: "Status is required." },
                { status: 400 }
            );
        }

        // Find the job
        const job = await prisma.job.findUnique({
            where: { id: jobId },
        });

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

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

        // Employers can only change status of admin-approved jobs
        const allowedSourceStatuses = Object.keys(VALID_TRANSITIONS);
        if (!allowedSourceStatuses.includes(job.status)) {
            return NextResponse.json(
                {
                    error: `Cannot change status of a job that is "${job.status}". Only admin-approved jobs (published, suspended) can have their status changed.`,
                },
                { status: 400 }
            );
        }

        // Check if the transition is valid
        const validTargets = VALID_TRANSITIONS[job.status] || [];
        if (!validTargets.includes(status)) {
            return NextResponse.json(
                {
                    error: `Cannot change status from "${job.status}" to "${status}". Valid transitions: ${validTargets.join(", ") || "none"}.`,
                },
                { status: 400 }
            );
        }

        // Update the status
        const updatedJob = await prisma.job.update({
            where: { id: jobId },
            data: { status },
        });

        // Audit log
        await prisma.auditLog.create({
            data: {
                user_id: currentUser.id,
                action: "job.status_changed_by_employer",
                resource_type: "job",
                resource_id: jobId,
                details: {
                    oldStatus: job.status,
                    newStatus: status,
                },
                ip_address:
                    request.headers.get("x-forwarded-for") || "unknown",
            },
        });

        return NextResponse.json({
            success: true,
            message: `Job status changed to "${status}" successfully.`,
            job: updatedJob,
        });
    } catch (error: any) {
        console.error("Error changing job status:", error);
        return NextResponse.json(
            { error: "Internal server error", details: error.message },
            { status: 500 }
        );
    }
}
