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

// 영업목표 등록/수정 (원본: saveYearGoalInfo)
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 year = String(body.Year || body.year || "");
  const price = String(body.PRICE || body.price || "0");
  const objid = String(body.YEAR_GOAL_OBJID || body.objid || "");

  if (!year) return NextResponse.json({ success: false, message: "YEAR 누락" }, { status: 400 });

  const finalObjid = objid || createObjectId();

  const client = await pool.connect();
  try {
    await client.query(
      `INSERT INTO pms_pjt_year_goal (objid, year, operation_division_code, price, writer, regdate)
       VALUES ($1, $2, '', $3, $4, now())
       ON CONFLICT (objid) DO UPDATE SET
         year = EXCLUDED.year,
         price = EXCLUDED.price`,
      [finalObjid, year, price, user.userId]
    );
    return NextResponse.json({ success: true, message: "저장되었습니다.", objid: finalObjid });
  } catch (e) {
    console.error("YearGoal save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
