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



export async function PUT(req, { params }) {
  const { id } = await params;  // Extracting the `id` from the URL parameters

  try {
    const data = await req.json();  // Extract the data from the request body

    // Check which field is being updated
    let query = '';
    let queryParams = [];
    
    if (typeof data.popular !== 'undefined') {
      // Ensure that `popular` field is passed in the body
      if (typeof data.popular !== 'boolean') {
        return NextResponse.json({ success: false, message: "'popular' must be a boolean value" }, { status: 400 });
      }
      const popularValue = data.popular ? 1 : 0;
      query = `UPDATE courses SET popular = ? WHERE id = ?`;
      queryParams = [popularValue, id];
    } 
    else if (typeof data.country_popular !== 'undefined') {
      // Ensure that `country_popular` field is passed in the body
      if (typeof data.country_popular !== 'boolean') {
        return NextResponse.json({ success: false, message: "'country_popular' must be a boolean value" }, { status: 400 });
      }
      const countryPopularValue = data.country_popular ? 1 : 0;
      query = `UPDATE courses SET country_popular = ? WHERE id = ?`;
      queryParams = [countryPopularValue, id];
    }
    else {
      return NextResponse.json({ success: false, message: "Either 'popular' or 'country_popular' must be provided" }, { status: 400 });
    }

    // Execute the query using the pool
    const [result] = await pool.execute<ResultSetHeader>(query, queryParams);

    // Check if any rows were affected
    if (result.affectedRows === 0) {
      return NextResponse.json({ success: false, message: 'Course not found or no changes made' }, { status: 404 });
    }

    // Fetch the updated course to return it
    const [updatedCourse] = await pool.query("SELECT * FROM courses WHERE id = ?", [id]);

    return NextResponse.json({ 
      success: true, 
      message: "Course status updated successfully",
      data: updatedCourse[0]
    });
  } catch (error) {
    console.error('Error updating course status:', error);
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}