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

// 프로젝트 수정 조회/저장 (project.getProjectModifyInfo + ModifyProject 대응)
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 action = String(body.action || "detail");

  if (action === "save") {
    const { objId, project_name, facility, facility_qty, facility_depth,
            contract_del_date, contract_currency, contract_price, contract_price_currency } = body;
    if (!objId) return NextResponse.json({ success: false, message: "objId 필요" }, { status: 400 });
    try {
      await execute(
        `UPDATE project_mgmt SET
          project_name = $1,
          facility = $2,
          facility_qty = $3,
          facility_depth = $4,
          contract_del_date = $5,
          contract_currency = $6,
          contract_price = $7,
          contract_price_currency = $8
         WHERE objid = $9`,
        [
          String(project_name || ""),
          String(facility || ""),
          String(facility_qty || "").replace(/,/g, ""),
          String(facility_depth || "").replace(/,/g, ""),
          String(contract_del_date || ""),
          String(contract_currency || ""),
          String(contract_price || "").replace(/,/g, ""),
          String(contract_price_currency || "").replace(/,/g, ""),
          String(objId),
        ],
      );
      return NextResponse.json({ success: true, message: "저장되었습니다." });
    } catch (e) {
      console.error("Project modify save:", e);
      return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
    }
  }

  // detail
  const row = await queryOne<Record<string, unknown>>(
    `SELECT objid::text AS "OBJID",
            project_no AS "PROJECT_NO",
            project_name AS "PROJECT_NAME",
            facility AS "FACILITY",
            facility_qty AS "FACILITY_QTY",
            facility_depth AS "FACILITY_DEPTH",
            contract_del_date AS "CONTRACT_DEL_DATE",
            contract_currency AS "CONTRACT_CURRENCY",
            contract_price AS "CONTRACT_PRICE",
            contract_price_currency AS "CONTRACT_PRICE_CURRENCY"
       FROM project_mgmt
      WHERE objid = $1`,
    [String(body.objId || "")],
  );
  return NextResponse.json({ success: true, data: row ?? {} });
}
