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

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.actionType === "regist" || !body.objId;

  try {
    if (isNew) {
      if (body.product_code) {
        const dup = await queryOne(`SELECT COUNT(*) AS cnt FROM product_mgmt WHERE product_code = $1`, [body.product_code]);
        if (Number(dup?.cnt || 0) > 0) {
          return NextResponse.json({ success: false, message: "이미 등록된 제품코드입니다." });
        }
      }

      const objId = createObjectId();
      await execute(
        `INSERT INTO product_mgmt (objid, product_category, product_type, product_name,
          product_code, product_name_code, product_grade, product_ton, product_boom,
          product_vehicle, production_flag, note, writer, regdate)
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, now())`,
        [objId, body.product_category||"", body.product_type||"",
         body.product_name||"", body.product_code||"", body.product_name_code||"",
         body.product_grade||"", body.product_ton||"", body.product_boom||"",
         body.product_vehicle||"", body.production_flag||"", body.note||"",
         user.userId]
      );
      return NextResponse.json({ success: true, objId, message: "등록되었습니다." });
    } else {
      await execute(
        `UPDATE product_mgmt SET
          product_category=$1, product_type=$2, product_name=$3, product_code=$4,
          product_name_code=$5, product_grade=$6, product_ton=$7, product_boom=$8,
          product_vehicle=$9, production_flag=$10, note=$11
         WHERE objid=$12`,
        [body.product_category||"", body.product_type||"",
         body.product_name||"", body.product_code||"", body.product_name_code||"",
         body.product_grade||"", body.product_ton||"", body.product_boom||"",
         body.product_vehicle||"", body.production_flag||"", body.note||"",
         body.objId]
      );
      return NextResponse.json({ success: true, message: "수정되었습니다." });
    }
  } catch (error) {
    console.error("Product save error:", error);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." });
  }
}
