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 CM.objid::text AS "OBJID", CM.contract_no AS "PROJECT_NO",
       CM.project_name AS "PROJECT_NAME",
       COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = CM.customer_objid LIMIT 1), '') AS "CUSTOMER_NAME",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = CM.product LIMIT 1), '') AS "INSPECTION_TYPE_NAME",
       CM.contract_del_date AS "INSPECTION_DATE",
       CM.product AS "PRODUCT", CM.facility_qty AS "QTY",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = CM.pm_user_id LIMIT 1), '') AS "WRITER_NAME"
     FROM contract_mgmt CM WHERE CM.objid::text = $1`, [objId]
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });
  return NextResponse.json({ success: true, data: info });
}
