import { NextRequest, NextResponse } from "next/server";
import { queryRows, execute } from "@/lib/db";
import { getSession } from "@/lib/session";

// 사인 조회 (materialRequestDetailPopUpsign) / 저장 (savesignInventoryTransfer) / 삭제 (materialRequestDetailPopUpsigndelete)
// 원본: inventoryMng.xml line 2082, 1883, 2093
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 action = String(body.action || "list");

  if (action === "list") {
    // OBJID들의 사인 목록
    const checkArr: string[] = Array.isArray(body.checkArr)
      ? body.checkArr.map(String)
      : String(body.checkArr || "")
          .split(",")
          .map((s: string) => s.trim())
          .filter(Boolean);
    if (checkArr.length === 0) return NextResponse.json([]);
    const ph = checkArr.map((_, i) => `$${i + 1}`).join(",");
    const rows = await queryRows(
      `SELECT objid AS "OBJID", acq_user AS "ACQ_USER", sign AS "SIGN"
         FROM inventory_mgmt_out
        WHERE objid IN (${ph})`,
      checkArr,
    );
    return NextResponse.json(rows);
  }

  if (action === "save") {
    // 단일 또는 다중 OBJID에 사인 저장
    const lines: Array<{ OBJID: string; ACQ_USER: string; SIGN: string }> = Array.isArray(body.lines)
      ? body.lines
      : [];
    try {
      for (const line of lines) {
        await execute(
          `INSERT INTO inventory_mgmt_out (objid, acq_user, sign)
           VALUES ($1, $2, $3)
           ON CONFLICT (objid) DO UPDATE SET
             acq_user = EXCLUDED.acq_user,
             sign = EXCLUDED.sign`,
          [line.OBJID, line.ACQ_USER || "", line.SIGN || ""],
        );
      }
      return NextResponse.json({ success: true, message: "사인이 등록 되었습니다." });
    } catch (e) {
      console.error("sign save:", e);
      return NextResponse.json(
        { success: false, message: "오류가 발생하였습니다." },
        { status: 500 },
      );
    }
  }

  if (action === "delete") {
    const objIds: string[] = Array.isArray(body.objIds) ? body.objIds.map(String) : [];
    try {
      for (const objId of objIds) {
        await execute(
          `INSERT INTO inventory_mgmt_out (objid, sign)
           VALUES ($1, '')
           ON CONFLICT (objid) DO UPDATE SET sign = ''`,
          [objId],
        );
      }
      return NextResponse.json({ success: true, message: "삭제되었습니다.", result: "true" });
    } catch (e) {
      console.error("sign delete:", e);
      return NextResponse.json(
        { success: false, message: "오류가 발생하였습니다." },
        { status: 500 },
      );
    }
  }

  return NextResponse.json({ success: false, message: "지원하지 않는 action" }, { status: 400 });
}
