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

// WBS Task 조회/저장 (pms_wbs_task)
// - action: list | save
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 pms_wbs_task SET
             task_name = $1,
             design_user_id = $2, design_plan_start = $3, design_plan_end = $4, design_act_start = $5, design_act_end = $6, design_rate = $7,
             purchase_user_id = $8, purchase_plan_start = $9, purchase_plan_end = $10, purchase_act_start = $11, purchase_act_end = $12, purchase_rate = $13,
             produce_user_id = $14, produce_plan_start = $15, produce_plan_end = $16, produce_act_start = $17, produce_act_end = $18, produce_rate = $19
           WHERE objid = $20`,
          [
            String(r.TASK_NAME || ""),
            String(r.DESIGN_USER_ID || ""), String(r.DESIGN_PLAN_START || ""), String(r.DESIGN_PLAN_END || ""), String(r.DESIGN_ACT_START || ""), String(r.DESIGN_ACT_END || ""), String(r.DESIGN_RATE || ""),
            String(r.PURCHASE_USER_ID || ""), String(r.PURCHASE_PLAN_START || ""), String(r.PURCHASE_PLAN_END || ""), String(r.PURCHASE_ACT_START || ""), String(r.PURCHASE_ACT_END || ""), String(r.PURCHASE_RATE || ""),
            String(r.PRODUCE_USER_ID || ""), String(r.PRODUCE_PLAN_START || ""), String(r.PRODUCE_PLAN_END || ""), String(r.PRODUCE_ACT_START || ""), String(r.PRODUCE_ACT_END || ""), String(r.PRODUCE_RATE || ""),
            String(r.OBJID || ""),
          ],
        );
      }
      return NextResponse.json({ success: true, message: "저장되었습니다." });
    } catch (e) {
      console.error("wbs-task save:", e);
      return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
    }
  }

  // list
  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 code_name FROM comm_code WHERE code_id = category_cd LIMIT 1) AS "CATEGORY_NAME",
            (SELECT supply_name FROM supply_mng WHERE objid::text = customer_objid LIMIT 1) AS "CUSTOMER_NAME",
            contract_del_date AS "CONTRACT_DEL_DATE"
       FROM project_mgmt WHERE objid = $1`,
    [contractObjId],
  );

  const rows = await queryRows<Record<string, unknown>>(
    `SELECT T.objid::text AS "OBJID",
            T.parent_objid::text AS "PARENT_OBJID",
            T.task_name AS "TASK_NAME",
            T.unit_no AS "UNIT_NO",
            T.design_user_id AS "DESIGN_USER_ID",
            (SELECT user_name FROM user_info WHERE user_id = T.design_user_id LIMIT 1) AS "DESIGN_USER_NAME",
            T.design_plan_start AS "DESIGN_PLAN_START",
            T.design_plan_end AS "DESIGN_PLAN_END",
            T.design_act_start AS "DESIGN_ACT_START",
            T.design_act_end AS "DESIGN_ACT_END",
            T.design_rate AS "DESIGN_RATE",
            T.purchase_user_id AS "PURCHASE_USER_ID",
            (SELECT user_name FROM user_info WHERE user_id = T.purchase_user_id LIMIT 1) AS "PURCHASE_USER_NAME",
            T.purchase_plan_start AS "PURCHASE_PLAN_START",
            T.purchase_plan_end AS "PURCHASE_PLAN_END",
            T.purchase_act_start AS "PURCHASE_ACT_START",
            T.purchase_act_end AS "PURCHASE_ACT_END",
            T.purchase_rate AS "PURCHASE_RATE",
            T.produce_user_id AS "PRODUCE_USER_ID",
            (SELECT user_name FROM user_info WHERE user_id = T.produce_user_id LIMIT 1) AS "PRODUCE_USER_NAME",
            T.produce_plan_start AS "PRODUCE_PLAN_START",
            T.produce_plan_end AS "PRODUCE_PLAN_END",
            T.produce_act_start AS "PRODUCE_ACT_START",
            T.produce_act_end AS "PRODUCE_ACT_END",
            T.produce_rate AS "PRODUCE_RATE"
       FROM pms_wbs_task T
      WHERE T.contract_objid = $1
      ORDER BY T.unit_no NULLS LAST, T.task_name`,
    [contractObjId],
  );

  // Master 행(집계) 생성 — 원본 project.getProjectProductTaskList UNION 로직 대응
  // 시작일 MIN, 종료일 MAX, 진척율 평균(ROUND 1자리)
  const master = buildMasterRow(rows);
  const resultList = master ? [master, ...rows.map((r) => ({ ...r, IS_MASTER: "0" }))] : rows;

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

function buildMasterRow(rows: Record<string, unknown>[]): Record<string, unknown> | null {
  if (rows.length === 0) return null;

  const minDate = (field: string) => {
    const vals = rows.map((r) => String(r[field] ?? "")).filter((v) => v !== "");
    return vals.length === 0 ? "" : vals.reduce((a, b) => (a < b ? a : b));
  };
  const maxDate = (field: string) => {
    const vals = rows.map((r) => String(r[field] ?? "")).filter((v) => v !== "");
    return vals.length === 0 ? "" : vals.reduce((a, b) => (a > b ? a : b));
  };
  const avgRate = (field: string) => {
    const nums = rows.map((r) => parseFloat(String(r[field] ?? "0")) || 0);
    if (nums.length === 0) return "";
    const avg = nums.reduce((a, b) => a + b, 0) / nums.length;
    return String(Math.round(avg * 10) / 10);
  };

  return {
    IS_MASTER: "1",
    OBJID: "",
    TASK_NAME: "",
    UNIT_NO: "",
    DESIGN_PLAN_START: minDate("DESIGN_PLAN_START"),
    DESIGN_PLAN_END: maxDate("DESIGN_PLAN_END"),
    DESIGN_ACT_START: minDate("DESIGN_ACT_START"),
    DESIGN_ACT_END: maxDate("DESIGN_ACT_END"),
    DESIGN_RATE: avgRate("DESIGN_RATE"),
    PURCHASE_PLAN_START: minDate("PURCHASE_PLAN_START"),
    PURCHASE_PLAN_END: maxDate("PURCHASE_PLAN_END"),
    PURCHASE_ACT_START: minDate("PURCHASE_ACT_START"),
    PURCHASE_ACT_END: maxDate("PURCHASE_ACT_END"),
    PURCHASE_RATE: avgRate("PURCHASE_RATE"),
    PRODUCE_PLAN_START: minDate("PRODUCE_PLAN_START"),
    PRODUCE_PLAN_END: maxDate("PRODUCE_PLAN_END"),
    PRODUCE_ACT_START: minDate("PRODUCE_ACT_START"),
    PRODUCE_ACT_END: maxDate("PRODUCE_ACT_END"),
    PRODUCE_RATE: avgRate("PRODUCE_RATE"),
  };
}
