import { NextResponse } from "next/server";
import { db } from "@/app/lib/db";

function normalize(input: string) {
  return String(input || "")
    .trim()
    .replace(/\r/g, "")
    .replace(/\n/g, "")
    .replace(/\t/g, "")
    .replace(/\s+/g, "")
    .replace(/"/g, "")          // 🔥 hapus tanda petik
    .replace(/'/g, "")          // 🔥 hapus apostrophe
    .toUpperCase();
}

export async function GET(
  req: Request,
  { params }: { params: Promise<{ barcode: string }> }
) {
  try {
    const { barcode } = await params;

    const raw = decodeURIComponent(barcode || "");
    const clean = normalize(raw);

    if (!clean) {
      return NextResponse.json(
        { message: "Barcode kosong" },
        { status: 400 }
      );
    }

    const [rows]: any = await db.query(
      `
      SELECT 
        i.id,
        i.sku,
        i.name,
        i.unit,
        i.description,
        c.name AS category,
        b.barcode
      FROM items i
      LEFT JOIN item_barcodes b ON b.item_id = i.id
      LEFT JOIN categories c ON c.id = i.category_id
      WHERE
        UPPER(
          REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
            IFNULL(b.barcode,''),

            ' ', ''),
            '\n',''),
            '\r',''),
            '\t',''),
            '"',''),
            '''','')
        ) = ?

        OR

        UPPER(
          REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
            IFNULL(i.sku,''),

            ' ', ''),
            '\n',''),
            '\r',''),
            '\t',''),
            '"',''),
            '''','')
        ) = ?

        OR

        UPPER(
          REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
            IFNULL(b.barcode,''),

            ' ', ''),
            '\n',''),
            '\r',''),
            '\t',''),
            '"',''),
            '''','')
        ) LIKE CONCAT('%', ?, '%')

      ORDER BY b.is_primary DESC, b.id ASC
      LIMIT 1
      `,
      [clean, clean, clean]
    );

    const item = rows?.[0] || null;

    return NextResponse.json({
      success: !!item,
      item,
      debug: {
        raw,
        clean,
        found: !!item,
        db_barcode: item?.barcode || null,
        db_sku: item?.sku || null,
      },
      message: item ? "OK" : "Item ditemukan",
    });
  } catch (err: any) {
    return NextResponse.json(
      {
        message: "Scan gagal",
        error: err.message,
      },
      { status: 500 }
    );
  }
}