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

// 영업목표 조회/저장 (contractMgmt.getYearGoalInfo + saveYearGoalInfo 이식)
// 테이블: PMS_PJT_YEAR_GOAL (OBJID, YEAR, OPERATION_DIVISION_CODE, PRICE, WRITER, REGDATE)
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 || "list");

  if (action === "save") {
    const year = String(body.year || "");
    const price = String(body.price || "0").replace(/,/g, "");
    if (!year) return NextResponse.json({ success: false, message: "year 필요" }, { status: 400 });
    try {
      const objId = String(body.objId || createObjectId());
      await execute(
        `INSERT INTO pms_pjt_year_goal (objid, year, operation_division_code, price, writer, regdate)
         VALUES ($1, $2, $3, $4, $5, NOW())
         ON CONFLICT (objid) DO UPDATE SET price = EXCLUDED.price`,
        [objId, year, String(body.operation_division_code || ""), price, user.userId],
      );
      return NextResponse.json({ success: true, message: "저장되었습니다." });
    } catch (e) {
      console.error("year-goal save:", e);
      return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
    }
  }

  if (action === "delete") {
    const objIds: string[] = Array.isArray(body.objIds) ? body.objIds : [];
    if (objIds.length === 0) return NextResponse.json({ success: false, message: "선택된 항목 없음" });
    try {
      const ph = objIds.map((_, i) => `$${i + 1}`).join(",");
      await execute(`DELETE FROM pms_pjt_year_goal WHERE objid IN (${ph})`, objIds);
      return NextResponse.json({ success: true, message: "삭제되었습니다." });
    } catch (e) {
      console.error("year-goal delete:", e);
      return NextResponse.json({ success: false, message: "삭제 중 오류가 발생했습니다." }, { status: 500 });
    }
  }

  // list
  const rows = await queryRows(
    `SELECT objid::text AS "OBJID",
            year AS "YEAR",
            operation_division_code AS "OPERATION_DIVISION_CODE",
            price AS "PRICE",
            writer AS "WRITER",
            TO_CHAR(regdate, 'YYYY-MM-DD') AS "REGDATE"
       FROM pms_pjt_year_goal
      ORDER BY year DESC`,
  );
  return NextResponse.json({ RESULTLIST: rows });
}
