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

// 원본: salesMng.mergeSalesRequestMasterInfo + salesMng.initSalesRequestPart + salesMng.mergeSalesRequestPartInfo
interface PartRow {
  OBJID?: string;
  SALES_BOM_QTY_OBJID?: string;
  PART_OBJID?: string;
  PART_NAME?: string;
  QTY?: string | number;
  ORG_QTY?: string | number;
  PARTNER_OBJID?: string;
  DELIVERY_REQUEST_DATE?: string;
  REMARK?: string;
}

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() : String(body.objId);
  const status = String(body.status || "create");
  const parts: PartRow[] = Array.isArray(body.parts) ? body.parts : [];

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

    await client.query(
      `INSERT INTO sales_request_master (
         objid, request_mng_no, request_cd, project_no, release_date,
         request_reasons, request_user_id, delivery_request_date, unit_name,
         status, writer, remark, regdate
       ) VALUES (
         $1,
         (SELECT 'R' || TO_CHAR(NOW(),'YYYYMMDD') || '-' || LPAD((COALESCE(MAX(SUBSTR(request_mng_no, 11, 13))::integer, 0) + 1)::text, 3, '0')
            FROM sales_request_master
            WHERE request_mng_no LIKE 'R' || TO_CHAR(NOW(),'YYYYMMDD') || '-%'),
         $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, now()
       )
       ON CONFLICT (objid) DO UPDATE SET
         request_cd = EXCLUDED.request_cd,
         project_no = EXCLUDED.project_no,
         release_date = EXCLUDED.release_date,
         request_reasons = EXCLUDED.request_reasons,
         request_user_id = EXCLUDED.request_user_id,
         delivery_request_date = EXCLUDED.delivery_request_date,
         unit_name = EXCLUDED.unit_name,
         status = EXCLUDED.status,
         remark = EXCLUDED.remark`,
      [
        masterObjId,
        String(body.request_cd || ""),
        String(body.project_no || ""),
        String(body.release_date || ""),
        String(body.request_reasons || ""),
        String(body.request_user_id || user.userId),
        String(body.delivery_request_date || ""),
        String(body.unit_name || ""),
        status,
        user.userId,
        String(body.remark || ""),
      ],
    );

    await client.query(`DELETE FROM sales_request_part WHERE sales_request_master_objid = $1`, [masterObjId]);

    for (const p of parts) {
      if (!p.PART_OBJID) continue;
      await client.query(
        `INSERT INTO sales_request_part (
           objid, sales_bom_qty_objid, part_objid, sales_request_master_objid,
           part_name, qty, org_qty, partner_objid,
           delivery_request_date, writer, regdate, status, remark
         ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now(), $11, $12)`,
        [
          createObjectId(),
          String(p.SALES_BOM_QTY_OBJID || ""),
          String(p.PART_OBJID || ""),
          masterObjId,
          String(p.PART_NAME || ""),
          String(p.QTY || "0"),
          String(p.ORG_QTY || p.QTY || "0"),
          String(p.PARTNER_OBJID || ""),
          String(p.DELIVERY_REQUEST_DATE || body.delivery_request_date || ""),
          status,
          String(p.REMARK || ""),
        ],
      );
    }

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