import { NextRequest, NextResponse } from "next/server";
import { pool } 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.objId || body.actionType === "regist";
  const objId = isNew ? createObjectId() : body.objId;

  const client = await pool.connect();
  try {
    let changeNo = body.change_no || "";
    if (isNew && !changeNo) {
      const year = new Date().getFullYear().toString().slice(2);
      const r = await client.query(
        `SELECT COALESCE(MAX(SUBSTR(change_no, 6)::numeric), 0)::int + 1 AS seq
         FROM design_change WHERE change_no LIKE $1`, [`DC${year}-%`]
      );
      changeNo = `DC${year}-${String(r.rows[0]?.seq || 1).padStart(4, "0")}`;
    }

    await client.query(
      `INSERT INTO design_change (
        objid, change_no, contract_objid, change_title, change_type, change_reason,
        request_date, request_user_id, status, writer, reg_date
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now())
      ON CONFLICT (objid) DO UPDATE SET
        change_title=EXCLUDED.change_title, change_type=EXCLUDED.change_type,
        change_reason=EXCLUDED.change_reason, status=EXCLUDED.status`,
      [objId, changeNo, body.contract_objid || body.project_no || "",
       body.change_title || "", body.change_type || "",
       body.change_reason || "", body.request_date || new Date().toISOString().slice(0, 10),
       body.request_user_id || user.userId, body.status || "draft", user.userId]
    );
    return NextResponse.json({ success: true, objId, changeNo, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("Design change save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally { client.release(); }
}
