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

// 인수이력 조회 (inventory_mgmt_out 기준)
// body: { partObjid, contractObjid, unitCode }
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 partObjid = String(body.partObjid || "");
  const contractObjid = String(body.contractObjid || "");
  const unitCode = String(body.unitCode || "");

  if (!partObjid || !contractObjid) {
    return NextResponse.json({ RESULTLIST: [], HEADER: {} });
  }

  // 헤더: 파트 기본 정보
  const header = await queryOne(
    `SELECT objid::text AS "OBJID",
            part_no AS "PART_NO",
            COALESCE(part_name,'') AS "PART_NAME",
            COALESCE(spec,'') AS "SPEC"
       FROM part_mng
      WHERE objid::varchar = $1`,
    [partObjid],
  );

  // 인수이력: IMO × IM, part+contract+unit 기준
  const params: unknown[] = [partObjid, contractObjid];
  let unitClause = "";
  if (unitCode) {
    params.push(unitCode);
    unitClause = `AND IMO.unit = $3`;
  }
  const rows = await queryRows(
    `SELECT IMO.objid::text AS "OBJID",
            IMO.out_date AS "OUT_DATE",
            IMO.out_qty AS "OUT_QTY",
            IMO.unit AS "UNIT",
            (SELECT COALESCE(O.unit_no,'') || '-' || COALESCE(O.task_name,'') FROM pms_wbs_task O WHERE O.objid = IMO.unit LIMIT 1) AS "UNIT_NAME",
            IMO.acq_user AS "ACQ_USER",
            COALESCE((SELECT user_name FROM user_info WHERE user_id = IMO.acq_user LIMIT 1), IMO.acq_user) AS "ACQ_USER_NAME",
            IMO.writer AS "WRITER",
            COALESCE((SELECT user_name FROM user_info WHERE user_id = IMO.writer LIMIT 1), IMO.writer) AS "WRITER_NAME",
            TO_CHAR(IMO.regdate, 'YYYY-MM-DD HH24:MI') AS "REG_DATE"
       FROM inventory_mgmt_out IMO
       JOIN inventory_mgmt IM ON IM.objid = IMO.parent_objid
      WHERE IMO.contract_mgmt_objid = $2
        AND IM.part_objid = $1
        ${unitClause}
      ORDER BY IMO.out_date DESC, IMO.regdate DESC`,
    params,
  );

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