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

// 발주서 저장 (purchaseOrder.mergePurchaseOrderMaster + mergePurchaseOrderPartInfo 대응)
// 발주번호 자동 생성: PO-YYMM-NNN
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 isNew = !body.objId || body.actionType === "regist";
  const masterObjId = isNew ? createObjectId() : body.objId;
  const parts: Record<string, unknown>[] = body.parts || [];

  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    // === 발주번호 생성 (신규시) ===
    let purchaseOrderNo = body.purchase_order_no || "";
    if (isNew && !purchaseOrderNo) {
      const prefix = `PO-${new Date().toISOString().slice(2, 4)}${String(new Date().getMonth() + 1).padStart(2, "0")}-`;
      const maxResult = await client.query(
        `SELECT MAX(
           CASE WHEN SPLIT_PART(purchase_order_no, '-', 3) = '' OR purchase_order_no IS NULL THEN '0'
                ELSE SPLIT_PART(purchase_order_no, '-', 3) END::numeric
         )::integer + 1 AS next_seq
         FROM purchase_order_master`
      );
      const nextSeq = maxResult.rows[0]?.next_seq || 1;
      purchaseOrderNo = `${prefix}${nextSeq}`;
    }

    // === 마스터 UPSERT ===
    await client.query(
      `INSERT INTO purchase_order_master (
        objid, purchase_order_no, title, type, order_type_cd, purchase_order_no_org,
        partner_objid, my_company_objid, contract_mgmt_objid, unit_code,
        delivery_date, delivery_place, effective_date, payment_terms,
        vat_method, remark, sales_mng_user_id,
        total_supply_unit_price, total_supply_price, total_real_supply_price,
        discount_price, total_price, nego_rate, total_price_txt,
        writer, regdate, status, project_no
      ) VALUES (
        $1, $2, $3, $4, $5, $6,
        $7, $8, $9::numeric, $10,
        $11, $12, $13, $14,
        $15, $16, $17,
        $18, $19, $20,
        $21, $22, $23, $24,
        $25, now(), $26, $27
      )
      ON CONFLICT (objid) DO UPDATE SET
        title = EXCLUDED.title,
        type = EXCLUDED.type,
        order_type_cd = EXCLUDED.order_type_cd,
        purchase_order_no_org = EXCLUDED.purchase_order_no_org,
        partner_objid = EXCLUDED.partner_objid,
        my_company_objid = EXCLUDED.my_company_objid,
        contract_mgmt_objid = EXCLUDED.contract_mgmt_objid,
        unit_code = EXCLUDED.unit_code,
        delivery_date = EXCLUDED.delivery_date,
        delivery_place = EXCLUDED.delivery_place,
        effective_date = EXCLUDED.effective_date,
        payment_terms = EXCLUDED.payment_terms,
        vat_method = EXCLUDED.vat_method,
        remark = EXCLUDED.remark,
        sales_mng_user_id = EXCLUDED.sales_mng_user_id,
        total_supply_unit_price = EXCLUDED.total_supply_unit_price,
        total_supply_price = EXCLUDED.total_supply_price,
        total_real_supply_price = EXCLUDED.total_real_supply_price,
        discount_price = EXCLUDED.discount_price,
        total_price = EXCLUDED.total_price,
        nego_rate = EXCLUDED.nego_rate,
        total_price_txt = EXCLUDED.total_price_txt,
        status = EXCLUDED.status,
        project_no = EXCLUDED.project_no`,
      [
        masterObjId, purchaseOrderNo, body.title || "", body.type || "",
        body.order_type_cd || "", body.purchase_order_no_org || "",
        body.partner_objid || "", body.my_company_objid || "",
        body.contract_mgmt_objid || null, body.unit_code || "",
        body.delivery_date || null, body.delivery_place || "",
        body.effective_date || null, body.payment_terms || "",
        body.vat_method || "", body.remark || "", body.sales_mng_user_id || "",
        body.total_supply_unit_price || "0", body.total_supply_price || "0",
        body.total_real_supply_price || "0",
        body.discount_price || "0", body.total_price || "0",
        body.nego_rate || "0", body.total_price_txt || "",
        user.userId, body.status || "create", body.project_no || "",
      ]
    );

    // === 기존 파트 삭제 후 재입력 (수정 시) ===
    if (!isNew) {
      await client.query(
        `DELETE FROM purchase_order_part WHERE purchase_order_master_objid = $1`,
        [masterObjId]
      );
    }

    // === 파트 INSERT ===
    for (const part of parts) {
      const partObjId = String(part.OBJID || part.objId || "") || createObjectId();
      await client.query(
        `INSERT INTO purchase_order_part (
          objid, purchase_order_master_objid, part_objid,
          part_no, part_name, spec, maker, unit,
          bom_qty, qty, order_qty, partner_price,
          price1, price2, price3, price4,
          supply_unit_price, supply_unit_vat_price, supply_unit_vat_sum_price,
          total_order_qty, stock_qty, real_order_qty, real_supply_price,
          remark, writer, regdate, status
        ) VALUES (
          $1, $2, $3,
          $4, $5, $6, $7, $8,
          REPLACE($9::varchar, ',', ''), REPLACE($10::varchar, ',', ''),
          REPLACE($11::varchar, ',', ''), REPLACE($12::varchar, ',', ''),
          REPLACE($13::varchar, ',', ''), REPLACE($14::varchar, ',', ''),
          REPLACE($15::varchar, ',', ''), REPLACE($16::varchar, ',', ''),
          REPLACE($17::varchar, ',', ''), REPLACE($18::varchar, ',', ''),
          REPLACE($19::varchar, ',', ''),
          REPLACE($20::varchar, ',', ''), REPLACE($21::varchar, ',', ''),
          REPLACE($22::varchar, ',', ''), REPLACE($23::varchar, ',', ''),
          $24, $25, now(), 'active'
        )`,
        [
          partObjId, masterObjId, String(part.PART_OBJID || ""),
          String(part.PART_NO || ""), String(part.PART_NAME || ""),
          String(part.SPEC || ""), String(part.MAKER || ""),
          String(part.UNIT || ""),
          String(part.BOM_QTY || "0"), String(part.QTY || "0"),
          String(part.ORDER_QTY || "0"), String(part.PARTNER_PRICE || "0"),
          String(part.PRICE1 || "0"), String(part.PRICE2 || "0"),
          String(part.PRICE3 || "0"), String(part.PRICE4 || "0"),
          String(part.SUPPLY_UNIT_PRICE || "0"), String(part.SUPPLY_UNIT_VAT_PRICE || "0"),
          String(part.SUPPLY_UNIT_VAT_SUM_PRICE || "0"),
          String(part.TOTAL_ORDER_QTY || "0"), String(part.STOCK_QTY || "0"),
          String(part.REAL_ORDER_QTY || "0"), String(part.REAL_SUPPLY_PRICE || "0"),
          String(part.REMARK || ""), user.userId,
        ]
      );
    }

    await client.query("COMMIT");

    return NextResponse.json({
      success: true,
      objId: masterObjId,
      purchaseOrderNo,
      message: isNew ? "등록되었습니다." : "수정되었습니다.",
    });
  } catch (error) {
    await client.query("ROLLBACK");
    console.error("Purchase order save error:", error);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
