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

// 투자비 관리 (project.investCostMngPopup 대응) — invest_cost_mng
// actions: list | save | delete
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");
  const targetObjId = String(body.targetObjId || "");

  if (action === "save") {
    const rows: Array<Record<string, unknown>> = Array.isArray(body.rows) ? body.rows : [];
    try {
      for (const r of rows) {
        const isNew = !r.objid;
        const objId = isNew ? createObjectId() : String(r.objid);
        if (isNew) {
          await execute(
            `INSERT INTO invest_cost_mng (objid, target_objid, seq, title, drafter, duedate, amount, status, writer, reg_date)
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())`,
            [objId, targetObjId, String(r.seq || ""), String(r.title || ""),
             String(r.drafter || ""), String(r.duedate || ""),
             String(r.amount || "").replace(/,/g, ""), String(r.status || "01"), user.userId],
          );
        } else {
          await execute(
            `UPDATE invest_cost_mng SET title=$1, drafter=$2, duedate=$3, amount=$4, status=$5, edit_date=now()
             WHERE objid=$6`,
            [String(r.title || ""), String(r.drafter || ""), String(r.duedate || ""),
             String(r.amount || "").replace(/,/g, ""), String(r.status || "01"), objId],
          );
        }
      }
      return NextResponse.json({ success: true, message: "저장되었습니다." });
    } catch (e) {
      console.error("invest-cost 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 invest_cost_mng WHERE objid IN (${ph})`, objIds);
      return NextResponse.json({ success: true, message: "삭제되었습니다." });
    } catch (e) {
      console.error("invest-cost delete:", e);
      return NextResponse.json({ success: false, message: "삭제 중 오류가 발생했습니다." }, { status: 500 });
    }
  }

  // list
  if (!targetObjId) return NextResponse.json({ RESULTLIST: [] });
  const rows = await queryRows(
    `SELECT objid::text AS "OBJID",
            seq AS "SEQ",
            title AS "TITLE",
            drafter AS "DRAFTER",
            (SELECT user_name FROM user_info WHERE user_id = drafter LIMIT 1) AS "DRAFTER_NAME",
            duedate AS "DUEDATE",
            amount AS "AMOUNT",
            status AS "STATUS",
            (SELECT COUNT(*) FROM attach_file_info WHERE target_objid = invest_cost_mng.objid::text AND doc_type = 'INVEST_FILE') AS "INVEST_FILE_CNT"
       FROM invest_cost_mng
      WHERE target_objid = $1
      ORDER BY seq::integer NULLS LAST`,
    [targetObjId],
  );

  return NextResponse.json({ RESULTLIST: rows });
}
