import { NextRequest } from "next/server";
import pool from "../../../../../lib/db/db";
import { ResultSetHeader } from "mysql2";

export async function DELETE(request: NextRequest, { params }) {
    try {
        const { id } = await params;
        const jobId = parseInt(id);

        if (isNaN(jobId)) {
            return new Response(
                JSON.stringify({ message: 'Invalid job ID' }),
                { status: 400 }
            );
        }

        const [result] = await pool.execute<ResultSetHeader>(
            'DELETE FROM job_opprtunities WHERE id = ?',
            [jobId]
        );

        if (result.affectedRows === 0) {
            return new Response(
                JSON.stringify({ message: 'Job not found' }),
                { status: 404 }
            );
        }

        return new Response(
            JSON.stringify({ message: 'Job deleted successfully' }),
            { status: 200 }
        );
    } catch (error) {
        console.error('Error deleting job:', error);
        return new Response(
            JSON.stringify({ 
                message: 'Failed to delete job', 
                details: error.message 
            }),
            { status: 500 }
        );
    }
}

export async function PUT(request: NextRequest, { params }) {
    try {
        const { id } = await params;
        const jobId = parseInt(id);
        
        if (isNaN(jobId)) {
            return new Response(
                JSON.stringify({ message: 'Invalid job ID' }),
                { status: 400 }
            );
        }

        const body = await request.json();
        console.log('Received update data:', body);
        
        let {
            title, job_type, city, province, country,
            site_based, skills, experience, image,
            requirements, responsibilities, description, active
        } = body;

        // Validate required fields
        if (!title || !job_type) {
            return new Response(
                JSON.stringify({ message: "Title and job_type are required" }),
                { status: 400 }
            );
        }

        // Parse skills if it's an array
        if (Array.isArray(skills)) {
            skills = skills.join(",");
        } else if (typeof skills === "string") {
            try {
                const parsedSkills = JSON.parse(skills);
                if (Array.isArray(parsedSkills)) {
                    skills = parsedSkills.join(",");
                }
            } catch {
                // If it's already a comma-separated string, keep it as is
            }
        } else {
            skills = "";
        }

        const query = `
            UPDATE job_opprtunities
            SET
                title = ?,
                job_type = ?,
                city = ?,
                province = ?,
                country = ?,
                site_based = ?,
                skills = ?,
                experience = ?,
                image = ?,
                requirements = ?,
                responsibilities = ?,
                description = ?,
                post_status = ?
            WHERE id = ?
        `;

        const values = [
            title.trim(),
            job_type.trim(),
            city?.trim() || "",
            province?.trim() || "",
            country?.trim() || "",
            site_based || "onsite",
            skills,
            experience?.trim() || "",
            image || null,
            requirements || "",
            responsibilities || "",
            description || "",
            active ? 1 : 0,
            jobId
        ];

        console.log('Executing update with values:', values);

        const [rows] = await pool.query<ResultSetHeader>(query, values);

        if (rows.affectedRows === 0) {
            return new Response(
                JSON.stringify({ message: "Job not found or no changes made" }),
                { status: 404 }
            );
        }

        return new Response(
            JSON.stringify({ 
                message: "Job updated successfully",
                id: jobId,
                ...body
            }),
            { status: 200 }
        );
    } catch (error) {
        console.error('Error updating job:', error);
        return new Response(
            JSON.stringify({ 
                message: "Failed to update job",
                details: error.message 
            }),
            { status: 500 }
        );
    }
}

// Additional endpoint for partial updates (like active status toggle)
export async function PATCH(request: NextRequest, { params }) {
    try {
        const { id } = await params;
        const jobId = parseInt(id);
        
        if (isNaN(jobId)) {
            return new Response(
                JSON.stringify({ message: 'Invalid job ID' }),
                { status: 400 }
            );
        }

        const body = await request.json();
        const { active } = body;

        if (typeof active !== 'boolean') {
            return new Response(
                JSON.stringify({ message: "Active status is required" }),
                { status: 400 }
            );
        }

        const query = `
            UPDATE job_opprtunities
            SET post_status = ?
            WHERE id = ?
        `;

        const values = [active ? 1 : 0, jobId];

        const [rows] = await pool.query<ResultSetHeader>(query, values);

        if (rows.affectedRows === 0) {
            return new Response(
                JSON.stringify({ message: "Job not found" }),
                { status: 404 }
            );
        }

        return new Response(
            JSON.stringify({ 
                message: "Job status updated successfully",
                active: active
            }),
            { status: 200 }
        );
    } catch (error) {
        console.error('Error updating job status:', error);
        return new Response(
            JSON.stringify({ 
                message: "Failed to update job status",
                details: error.message 
            }),
            { status: 500 }
        );
    }
}