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

// 목표가 저장 (procurStandMgmt.saveCostGoalInfo 대응)
// body: { contract_objid, material_cost_goal, labor_cost_goal, expense_cost_goal }
// input_cost_goal 테이블에 contract_objid 유니크 제약 없으므로 수동 upsert
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 contractObjid = String(body.contract_objid || "").trim();
  if (!contractObjid) {
    return NextResponse.json({ success: false, message: "프로젝트가 선택되지 않았습니다." }, { status: 400 });
  }

  // 콤마 제거
  const strip = (v: unknown) => String(v ?? "").replace(/,/g, "");
  const material = strip(body.material_cost_goal) || "0";
  const labor = strip(body.labor_cost_goal) || "0";
  const expense = strip(body.expense_cost_goal) || "0";

  try {
    const existing = await queryOne<{ OBJID: string }>(
      `SELECT objid::text AS "OBJID" FROM input_cost_goal WHERE contract_objid = $1 LIMIT 1`,
      [contractObjid]
    );
    if (existing) {
      await execute(
        `UPDATE input_cost_goal
            SET material_cost_goal = $1,
                labor_cost_goal = $2,
                expense_cost_goal = $3,
                writer = $4,
                regdate = NOW()
          WHERE objid::text = $5`,
        [material, labor, expense, user.userId, existing.OBJID]
      );
      return NextResponse.json({ success: true, message: "수정되었습니다." });
    }
    await execute(
      `INSERT INTO input_cost_goal
         (objid, contract_objid, material_cost_goal, labor_cost_goal, expense_cost_goal, writer, regdate)
       VALUES ($1, $2, $3, $4, $5, $6, NOW())`,
      [createObjectId(), contractObjid, material, labor, expense, user.userId]
    );
    return NextResponse.json({ success: true, message: "등록되었습니다." });
  } catch (error) {
    console.error("Cost goal save:", error);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
