import { NextRequest, NextResponse } from "next/server";
import { queryOne } 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 required" });

  const info = await queryOne(
    `SELECT AP.objid::text AS "OBJID",
       POM.purchase_order_no AS "PURCHASE_ORDER_NO",
       POP.part_no AS "PART_NO", POP.part_name AS "PART_NAME",
       AP.error_qty AS "ERROR_QTY", AP.error_reason AS "ERROR_REASON",
       AP.attribution AS "ATTRIBUTION", AP.receipt_qty AS "RECEIPT_QTY",
       AP.receipt_date AS "RECEIPT_DATE", AP.re_arrival_plan_date AS "RE_ARRIVAL_PLAN_DATE",
       AP.group_seq AS "GROUP_SEQ", AP.seq AS "SEQ"
     FROM arrival_plan AP
     JOIN purchase_order_part POP ON POP.objid::text = AP.order_part_objid
     JOIN purchase_order_master POM ON POM.objid = POP.purchase_order_master_objid
     WHERE AP.objid::text = $1`, [objId]
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });
  return NextResponse.json({ success: true, data: info });
}
