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

// 출고 등록/수정 (원본: releaseMgmt.xml saveReleaseMgmtInfo)
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 releaseObjId = String(body.RELEASE_OBJID || body.release_objid || "");
  const parentObjId = String(body.PARENT_OBJID || body.parent_objid || "");
  const product = String(body.PRODUCT || body.product || "");

  if (!releaseObjId) {
    return NextResponse.json({ success: false, message: "RELEASE_OBJID 누락" }, { status: 400 });
  }
  if (!parentObjId) {
    return NextResponse.json({ success: false, message: "계약 OBJID 누락" }, { status: 400 });
  }

  const releaseCarNo = String(body.RELEASE_CAR_NO || "");
  const releaseDate = String(body.RELEASE_DATE || "");
  const taskOverUserId = String(body.TASK_OVER_USER_ID || "");
  const taskOverDate = String(body.TASK_OVER_DATE || "");
  const taskOverComment = String(body.TASK_OVER_COMMENT || "");
  const installCompleteDate = String(body.INSTALL_COMPLETE_DATE || "");
  const installResult = String(body.INSTALL_RESULT || "");
  const productGroup = String(body.PRODUCT_GROUP || body.product_group || "");
  const status = String(body.STATUS || "0000201");

  const client = await pool.connect();
  try {
    await client.query(
      `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_group, product, install_complete_date, install_result)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, now(), $9, $10, $11, $12, $13)
       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_group = EXCLUDED.product_group,
         product = EXCLUDED.product,
         install_complete_date = EXCLUDED.install_complete_date,
         install_result = EXCLUDED.install_result`,
      [
        releaseObjId, parentObjId, releaseCarNo, releaseDate, taskOverUserId,
        taskOverDate, taskOverComment, status, user.userId,
        productGroup, product, installCompleteDate, installResult,
      ]
    );

    return NextResponse.json({ success: true, message: "저장되었습니다.", releaseObjId });
  } catch (e) {
    console.error("Release save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
