import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { getSession } from "@/lib/session";
import { createObjectId } from "@/lib/utils";

// 원본: /salesMng/saveSalesBomReportInfo.do — sales_bom_report_part UPSERT (공급업체 1~4 + 단가)
interface PartRow {
  OBJID?: string;
  PARENT_OBJID?: string;
  PART_OBJID?: string;
  PARENT_PART_NO?: string;
  CHILD_OBJID?: string;
  PRICE?: string;
  SUPPLY_OBJID?: string;
  PRICE1?: string;
  SUPPLY_OBJID1?: string;
  PRICE2?: string;
  SUPPLY_OBJID2?: string;
  PRICE3?: string;
  SUPPLY_OBJID3?: string;
  PRICE4?: string;
  SUPPLY_OBJID4?: string;
  PRICE_SUM?: string;
}

const stripComma = (v: unknown) => String(v ?? "").replace(/,/g, "");

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 parentObjId = String(body.parent_objId || body.PARENT_OBJID || "");
  const rows: PartRow[] = Array.isArray(body.rows) ? body.rows : [];
  if (!parentObjId) {
    return NextResponse.json({ success: false, message: "parent_objId가 필요합니다." });
  }

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    for (const r of rows) {
      const objid = String(r.OBJID || "").trim() || createObjectId();
      await client.query(
        `INSERT INTO sales_bom_report_part (
           objid, parent_objid, part_objid, parent_part_objid, bom_part_qty_objid,
           supply_objid, price, supply_objid1, price1, supply_objid2, price2,
           supply_objid3, price3, supply_objid4, price4,
           price_sum, writer, regdate
         ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,now())
         ON CONFLICT (objid) DO UPDATE SET
           supply_objid = EXCLUDED.supply_objid,
           price = EXCLUDED.price,
           supply_objid1 = EXCLUDED.supply_objid1,
           price1 = EXCLUDED.price1,
           supply_objid2 = EXCLUDED.supply_objid2,
           price2 = EXCLUDED.price2,
           supply_objid3 = EXCLUDED.supply_objid3,
           price3 = EXCLUDED.price3,
           supply_objid4 = EXCLUDED.supply_objid4,
           price4 = EXCLUDED.price4,
           price_sum = EXCLUDED.price_sum,
           modifier = $17,
           update_date = now()`,
        [
          objid,
          parentObjId,
          String(r.PART_OBJID || ""),
          String(r.PARENT_PART_NO || ""),
          String(r.CHILD_OBJID || ""),
          String(r.SUPPLY_OBJID || ""),
          stripComma(r.PRICE),
          String(r.SUPPLY_OBJID1 || ""),
          stripComma(r.PRICE1),
          String(r.SUPPLY_OBJID2 || ""),
          stripComma(r.PRICE2),
          String(r.SUPPLY_OBJID3 || ""),
          stripComma(r.PRICE3),
          String(r.SUPPLY_OBJID4 || ""),
          stripComma(r.PRICE4),
          stripComma(r.PRICE_SUM),
          user.userId,
        ],
      );
    }
    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: "저장되었습니다." });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("purchase/bom save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
