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 IM.objid::text AS "OBJID", IM.parent_objid AS "PARENT_OBJID",
       IM.price_sum AS "PRICE_SUM", IM.issuance_date AS "ISSUANCE_DATE",
       IM.status AS "STATUS", IM.group_seq AS "GROUP_SEQ",
       COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = CM.customer_objid LIMIT 1), '') AS "CUSTOMER_NAME",
       CM.contract_no AS "PROJECT_NO", CM.project_name AS "PROJECT_NAME",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = IM.writer LIMIT 1), '') AS "WRITER_NAME"
     FROM invoice_mgmt IM
     LEFT JOIN contract_mgmt CM ON CM.objid::text = IM.parent_objid
     WHERE IM.objid::text = $1`, [objId]
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });
  return NextResponse.json({ success: true, data: info });
}
