import { NextRequest, NextResponse } from "next/server";
import { getPool } from "@/lib/db";

export async function POST(req: NextRequest) {
  try {
    const pool = getPool();
    const rowIndexes: number[] = await req.json();

    if (!Array.isArray(rowIndexes) || rowIndexes.length === 0) {
      return NextResponse.json(
        { error: "Invalid or empty row_indexes array" },
        { status: 400 }
      );
    }

    const placeholders = rowIndexes.map(() => "?").join(",");
    const [gRows] = await pool.query(
      `SELECT G FROM final_barcode WHERE row_index IN (${placeholders})`,
      rowIndexes
    ) as unknown as [any[], any];

    const gList = gRows.map((r: any) => r.G).filter(Boolean);

    if (gList.length === 0) {
      return NextResponse.json({ success: true, updated: 0 });
    }

    const gPlaceholders = gList.map(() => "?").join(",");
    const [updateResult] = await pool.query(
      `UPDATE orders SET last_status = 'پرینت' WHERE G IN (${gPlaceholders})`,
      gList
    ) as unknown as [any, any];

    return NextResponse.json({
      success: true,
      updated: (updateResult as any).affectedRows || 0,
    });
  } catch (err) {
    console.error("Error in status2print:", err);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
