import { NextRequest, NextResponse } from "next/server";
import { db } from "@/app/lib/db";

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);

    const q = searchParams.get("q") || "";

    const [rows]: any = await db.query(
      `
      SELECT
        id,
        sku,
        name,
        unit

      FROM items

      WHERE
        is_active = 1
        AND (
          sku LIKE ?
          OR name LIKE ?
        )

      ORDER BY name ASC
      LIMIT 20
      `,
      [`%${q}%`, `%${q}%`]
    );

    return NextResponse.json({
      success: true,

      data: rows.map((row: any) => ({
        id: row.id,
        sku: row.sku,
        name: row.name,
        unit: row.unit,
      })),
    });
  } catch (error: any) {
    return NextResponse.json(
      {
        success: false,
        message: error.message,
      },
      { status: 500 }
    );
  }
}