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

// partMng save - partMngFormPopUp.jsp + partMngDetailPopUp.jsp fn_save() 대응
// actionType: "regist" | "update" | "changeDesign"
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 actionType = String(body.actionType || "");
  const isNew = actionType === "regist" || !body.OBJID;
  const isChangeDesign = actionType === "changeDesign";
  // 신규 등록도 클라이언트가 OBJID를 미리 만들어 보낸 경우 그대로 사용 (파일 사전 업로드 지원)
  const objId = isNew ? (String(body.OBJID || "") || createObjectId()) : String(body.OBJID);

  const params: (string | null)[] = [
    objId,
    body.PART_NO || "", body.PART_NAME || "", body.UNIT || "", body.QTY || "",
    body.SPEC || "", body.MATERIAL || "", body.WEIGHT || "",
    body.PART_TYPE || "", body.MAKER || "", body.POST_PROCESSING || "", body.REMARK || "",
    body.THICKNESS || "", body.WIDTH || "", body.HEIGHT || "",
    body.OUT_DIAMETER || "", body.IN_DIAMETER || "", body.LENGTH || "",
    body.MAJOR_CATEGORY || "", body.SUB_CATEGORY || "",
    body.PRODUCT_MGMT_OBJID || null, body.UPG_NO || null,
    body.CHANGE_TYPE || null, body.CHANGE_OPTION || null, body.REVISION || "",
    body.DESIGN_APPLY_POINT || null, body.DESIGN_DATE || null,
    body.MANAGEMENT_FLAG || null, body.SUPPLY_CODE || null, body.SUB_MATERIAL || "",
  ];

  try {
    if (isNew) {
      await execute(
        `INSERT INTO part_mng (
          objid, part_no, part_name, unit, qty, spec, material, weight,
          part_type, maker, post_processing, remark,
          thickness, width, height, out_diameter, in_diameter, length,
          major_category, sub_category,
          product_mgmt_objid, upg_no,
          change_type, change_option, revision,
          design_apply_point, design_date, management_flag, supply_code, sub_material,
          status, is_last, writer, reg_date
        ) VALUES (
          $1,$2,$3,$4,$5,$6,$7,$8,
          $9,$10,$11,$12,
          $13,$14,$15,$16,$17,$18,
          $19,$20,
          $21,$22,
          $23,$24,$25,
          $26,$27,$28,$29,$30,
          'create','1',$31,NOW()
        )`,
        [...params, user.userId],
      );
    } else if (isChangeDesign) {
      // 설계변경: 기존 레코드를 'changing' 상태로 마크하고 신규 OBJID로 새 버전 생성
      const newObjId = createObjectId();
      await execute(`UPDATE part_mng SET is_last = '0', status = 'changing' WHERE objid = $1`, [objId]);
      await execute(
        `INSERT INTO part_mng (
           objid, part_no, part_name, unit, qty, spec, material, weight,
           part_type, maker, post_processing, remark,
           thickness, width, height, out_diameter, in_diameter, length,
           major_category, sub_category,
           product_mgmt_objid, upg_no,
           change_type, change_option, revision,
           design_apply_point, design_date, management_flag, supply_code, sub_material,
           status, is_last, writer, reg_date
         )
         SELECT $1, part_no, part_name, $4, $5, $6, $7, $8,
                $9, $10, $11, $12,
                $13, $14, $15, $16, $17, $18,
                $19, $20, $21, $22, $23, $24,
                COALESCE(revision, 'RE') || (
                  (COALESCE((SELECT COUNT(*) FROM part_mng WHERE part_no = PM.part_no), 0) + 1)::text
                ),
                $26, $27, $28, $29, $30,
                'changing', '1', $31, NOW()
           FROM part_mng PM WHERE objid = $2`,
        [
          newObjId, objId, params[1], params[3], params[4], params[5], params[6], params[7],
          params[8], params[9], params[10], params[11], params[12], params[13], params[14],
          params[15], params[16], params[17], params[18], params[19], params[20], params[21],
          params[22], params[23], "auto",
          params[25], params[26], params[27], params[28], params[29],
          user.userId,
        ],
      );
      return NextResponse.json({ success: true, objId: newObjId, message: "설계변경 등록되었습니다." });
    } else {
      await execute(
        `UPDATE part_mng SET
          part_no=$2, part_name=$3, unit=$4, qty=$5,
          spec=$6, material=$7, weight=$8,
          part_type=$9, maker=$10, post_processing=$11, remark=$12,
          thickness=$13, width=$14, height=$15,
          out_diameter=$16, in_diameter=$17, length=$18,
          major_category=$19, sub_category=$20,
          product_mgmt_objid=$21, upg_no=$22,
          change_type=$23, change_option=$24, revision=$25,
          design_apply_point=$26, design_date=$27,
          management_flag=$28, supply_code=$29, sub_material=$30,
          edit_date=NOW()
        WHERE objid=$1`,
        params,
      );
    }

    return NextResponse.json({
      success: true,
      objId,
      message: isNew ? "등록되었습니다." : "수정되었습니다.",
    });
  } catch (e) {
    console.error("Part save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
