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

// 출고결과 저장 (release_mgmt UPSERT)
// body: { actionType, release_objid?, parent_objid, product, release_date, writer,
//         release_car_no?, task_over_user_id?, task_over_date?, task_over_comment?,
//         install_complete_date?, install_result? }
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.release_objid || body.actionType === "regist";
  const objId = isNew ? createObjectId() : String(body.release_objid);
  const writer = String(body.writer || user.userId);

  try {
    await execute(
      `INSERT INTO release_mgmt (
         objid, parent_objid, release_car_no, release_date,
         task_over_user_id, task_over_date, task_over_comment,
         status, regdate, writer, product,
         install_complete_date, install_result
       ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW(), $9, $10, $11, $12)
       ON CONFLICT (objid) DO UPDATE SET
         parent_objid = EXCLUDED.parent_objid,
         release_car_no = EXCLUDED.release_car_no,
         release_date = EXCLUDED.release_date,
         task_over_user_id = EXCLUDED.task_over_user_id,
         task_over_date = EXCLUDED.task_over_date,
         task_over_comment = EXCLUDED.task_over_comment,
         status = EXCLUDED.status,
         writer = EXCLUDED.writer,
         product = EXCLUDED.product,
         install_complete_date = EXCLUDED.install_complete_date,
         install_result = EXCLUDED.install_result`,
      [
        objId,
        body.parent_objid || "",
        body.release_car_no || "",
        body.release_date || "",
        body.task_over_user_id || "",
        body.task_over_date || "",
        body.task_over_comment || "",
        body.status || "active",
        writer,
        body.product || "",
        body.install_complete_date || "",
        body.install_result || "",
      ],
    );
    return NextResponse.json({ success: true, objId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("Release save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
