import { RowDataPacket } from "mysql2";
import pool from "../../../../lib/db/db";
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {

  const connection = await pool.getConnection();

  try {
    const { country } = await request.json();

    if (!country) {
      return NextResponse.json({ 
        success: false, 
        error: "Country name is required" 
      }, { status: 400 });
    }

    const [rows] = await connection.query<RowDataPacket[]>(
      `SELECT before_description, after_description 
       FROM countries 
       WHERE LOWER(country) = LOWER(?) OR LOWER(country) LIKE LOWER(?)`,
      [country.trim(), `%${country.trim()}%`]
    );

    if (rows.length === 0) {
      return NextResponse.json({ 
        success: true, 
        data: {
          before_description: "",
          after_description: ""
        }
      });
    }

    const countryData = rows[0];

    return NextResponse.json({
      success: true,
      data: {
        before_description: countryData.before_description || "",
        after_description: countryData.after_description || ""
      }
    });

  } catch (error) {
    console.error('❌ Country descriptions API error:', error);
    return NextResponse.json({
      success: false,
      error: "Failed to fetch country descriptions",
      details: error.message
    }, { status: 500 });
  }
}