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

// 셋업 WBS 조회/저장 (setup_wbs_task)
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 rows: Array<Record<string, unknown>> = Array.isArray(body.rows) ? body.rows : [];
    try {
      for (const r of rows) {
        await execute(
          `UPDATE setup_wbs_task SET
             task_name = $1,
             setup_plan_start = $2, setup_plan_end = $3,
             setup_act_start = $4, setup_act_end = $5,
             setup_rate = $6
           WHERE objid = $7`,
          [
            String(r.TASK_NAME || ""),
            String(r.SETUP_PLAN_START || ""), String(r.SETUP_PLAN_END || ""),
            String(r.SETUP_ACT_START || ""), String(r.SETUP_ACT_END || ""),
            String(r.SETUP_RATE || ""),
            String(r.OBJID || ""),
          ],
        );
      }
      return NextResponse.json({ success: true, message: "저장되었습니다." });
    } catch (e) {
      console.error("wbs-setup save:", e);
      return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
    }
  }

  const contractObjId = String(body.contractObjId || body.OBJID || "");
  if (!contractObjId) return NextResponse.json({ RESULTLIST: [], HEADER: {} });

  const header = await queryOne<Record<string, unknown>>(
    `SELECT project_no AS "PROJECT_NO", project_name AS "PROJECT_NAME",
            (SELECT supply_name FROM supply_mng WHERE objid::text = customer_objid LIMIT 1) AS "CUSTOMER_NAME"
       FROM project_mgmt WHERE objid = $1`,
    [contractObjId],
  );

  const rows = await queryRows(
    `SELECT T.objid::text AS "OBJID",
            T.parent_objid::text AS "PARENT_OBJID",
            T.task_name AS "TASK_NAME",
            T.setup_plan_start AS "SETUP_PLAN_START",
            T.setup_plan_end AS "SETUP_PLAN_END",
            T.setup_act_start AS "SETUP_ACT_START",
            T.setup_act_end AS "SETUP_ACT_END",
            T.setup_rate AS "SETUP_RATE"
       FROM setup_wbs_task T
      WHERE T.contract_objid = $1
        AND COALESCE(T.parent_objid, '') != ''
      ORDER BY T.task_name`,
    [contractObjId],
  );

  return NextResponse.json({ RESULTLIST: rows, HEADER: header ?? {} });
}
