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

// 원가관리 메인 (expenseDashBoardGrid 대응)
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 conditions: string[] = ["CM.contract_result = '0000964'"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.year) {
    conditions.push(`TO_CHAR(TO_DATE(CM.contract_date, 'YYYY-MM-DD'), 'YYYY') = $${idx++}`);
    params.push(body.year);
  }
  if (body.project_no) {
    conditions.push(`CM.contract_no LIKE '%' || $${idx++} || '%'`);
    params.push(body.project_no);
  }

  const where = conditions.join(" AND ");

  const rows = await queryRows(
    `SELECT CM.objid::text AS "OBJID",
       CM.contract_no AS "PROJECT_NO",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = CM.product LIMIT 1), '') AS "PRODUCT_NAME",
       -- 목표원가 (input_cost_goal)
       COALESCE((SELECT (COALESCE(NULLIF(material_cost_goal,'')::numeric,0)
                        + COALESCE(NULLIF(labor_cost_goal,'')::numeric,0)
                        + COALESCE(NULLIF(expense_cost_goal,'')::numeric,0))
                 FROM input_cost_goal WHERE contract_objid = CM.objid::text LIMIT 1), 0) AS "TARGET_COST",
       -- 실적원가 = 재료비 + 노무비 + 경비
       (COALESCE((SELECT SUM(COALESCE(NULLIF(POP.supply_unit_price,'')::numeric,0))
                  FROM purchase_order_part POP
                  JOIN purchase_order_master POM ON POM.objid = POP.purchase_order_master_objid
                  WHERE POM.contract_mgmt_objid = CM.objid AND POM.status = 'approvalComplete'), 0)
        + COALESCE((SELECT SUM(COALESCE(NULLIF(amount_payment,'')::numeric,0))
                    FROM expense_master WHERE project_mgmt_objid = CM.objid::text), 0)
       ) AS "ACTUAL_COST",
       TO_CHAR(CM.regdate, 'YYYY-MM-DD') AS "REGDATE"
     FROM contract_mgmt CM
     WHERE ${where}
     ORDER BY CM.regdate DESC
`,
    params
  );

  // JS에서 차이/달성율 계산
  const result = rows.map((r: Record<string, unknown>) => {
    const target = Number(r.TARGET_COST || 0);
    const actual = Number(r.ACTUAL_COST || 0);
    return {
      ...r,
      DIFF_COST: target - actual,
      ACHIEVE_RATE: target > 0 ? Math.round(actual / target * 100 * 10) / 10 : 0,
    };
  });

  return NextResponse.json({ RESULTLIST: result, TOTAL_CNT: result.length });
}
