import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";
import { getStdCategoryByAlias } from "@/lib/procurement-std";

// 구매품표준 중복체크 (procurStandMgmt.overlapStandardMng / overlapMaterialCode 대응)
// body: { mode: "code"|"material", objId, code_group?, code_id?, code_name?, material_code? }
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const mode = String(body.mode || "code");
  const objId = String(body.objId || "0");

  if (mode === "material") {
    const materialCode = String(body.material_code || "").trim().toUpperCase();
    if (!materialCode) return NextResponse.json({ duplicate: false });
    const rows = await queryRows(
      `SELECT objid::text AS "OBJID"
         FROM part_mng
        WHERE objid::text != $1
          AND REPLACE(TRIM(UPPER(part_no)), ' ', '') = REPLACE(TRIM(UPPER($2)), ' ', '')`,
      [objId, materialCode]
    );
    return NextResponse.json({ duplicate: rows.length > 0 });
  }

  // code mode
  const alias = String(body.code_group || "");
  const def = getStdCategoryByAlias(alias);
  if (!def) return NextResponse.json({ duplicate: false });

  const codeId = String(body.code_id || "").trim().toUpperCase();
  const codeName = String(body.code_name || "").trim();
  const rows = await queryRows(
    `SELECT objid::text AS "OBJID"
       FROM procurement_standard
      WHERE objid::text != $1
        AND category = $2
        AND (
          REPLACE(TRIM(UPPER(code_name)), ' ', '') = REPLACE(TRIM(UPPER($3)), ' ', '')
          OR REPLACE(TRIM(UPPER(code_id)), ' ', '') = REPLACE(TRIM(UPPER($4)), ' ', '')
        )`,
    [objId, def.category, codeName, codeId]
  );
  return NextResponse.json({ duplicate: rows.length > 0 });
}
