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

// 목표가 단건 조회 + 프로젝트 정보
// body: { contract_objid } — 실제는 project_mgmt.objid (DB 컬럼명이 오해의 소지 있음)
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 pmObjid = String(body.contract_objid || "");
  if (!pmObjid) return NextResponse.json({ success: true, data: null });

  const row = await queryOne(
    `SELECT PM.objid::text AS "OBJID",
            PM.project_no AS "PROJECT_NO",
            PM.project_name AS "PROJECT_NAME",
            COALESCE(NULLIF(G.material_cost_goal, ''), '0') AS "MATERIAL_COST_GOAL",
            COALESCE(NULLIF(G.labor_cost_goal, ''), '0') AS "LABOR_COST_GOAL",
            COALESCE(NULLIF(G.expense_cost_goal, ''), '0') AS "EXPENSE_COST_GOAL"
       FROM project_mgmt PM
       LEFT JOIN input_cost_goal G ON G.contract_objid = PM.objid::text
      WHERE PM.objid::text = $1`,
    [pmObjid]
  );
  return NextResponse.json({ success: true, data: row || null });
}
