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

// 재고 단건 조회 — 기본정보 + 자재투입이력 + 예측수량
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { objId } = await request.json();
  if (!objId) return NextResponse.json({ success: false, message: "objId 누락" }, { status: 400 });

  const info = await queryOne(
    `SELECT objid::text AS "OBJID",
       ld_part_name AS "LD_PART_NAME",
       spec AS "SPEC",
       form_no AS "FORM_NO",
       maker AS "MAKER",
       material_code AS "MATERIAL_CODE",
       supply_objid AS "SUPPLY_OBJID",
       (SELECT supply_name FROM admin_supply_mng WHERE objid::text = T1.supply_objid LIMIT 1) AS "SUPPLY_NAME",
       location AS "LOCATION",
       price AS "PRICE"
     FROM sales_long_delivery T1
     WHERE objid = $1`,
    [String(objId)]
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });

  const inputs = await queryRows(
    `SELECT objid AS "OBJID",
       contract_objid AS "CONTRACT_OBJID",
       (SELECT COALESCE(project_no, contract_no) FROM project_mgmt WHERE objid = I.contract_objid LIMIT 1) AS "PROJECT_NO",
       input_qty AS "INPUT_QTY",
       input_date AS "INPUT_DATE"
     FROM sales_long_delivery_input I
     WHERE parent_objid = $1
     ORDER BY input_date DESC, objid`,
    [String(objId)]
  );

  const predicts = await queryRows(
    `SELECT objid AS "OBJID",
       month AS "MONTH",
       use_place AS "USE_PLACE",
       contract_objid AS "CONTRACT_OBJID",
       (SELECT COALESCE(project_no, contract_no) FROM project_mgmt WHERE objid = P.contract_objid LIMIT 1) AS "PROJECT_NO",
       qty AS "QTY",
       note AS "NOTE"
     FROM sales_long_delivery_predict P
     WHERE parent_objid = $1
     ORDER BY month::numeric, objid`,
    [String(objId)]
  );

  return NextResponse.json({ success: true, info, inputs, predicts });
}
