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 body = await request.json();
  const objid = String(body.objid || "");
  if (!objid) return NextResponse.json({ success: false, message: "objid 누락" }, { status: 400 });

  const info = await queryOne(
    `SELECT objid::text AS "OBJID",
      supply_code AS "SUPPLY_CODE",
      supply_name AS "SUPPLY_NAME",
      area_cd AS "AREA_CD",
      charge_user_name AS "CHARGE_USER_NAME",
      bus_reg_no AS "BUS_REG_NO",
      reg_no AS "REG_NO",
      supply_busname AS "SUPPLY_BUSNAME",
      supply_stockname AS "SUPPLY_STOCKNAME",
      supply_address AS "SUPPLY_ADDRESS",
      supply_tel_no AS "SUPPLY_TEL_NO",
      email AS "EMAIL",
      office_no AS "OFFICE_NO",
      supply_fax_no AS "SUPPLY_FAX_NO",
      COALESCE(status,'active') AS "STATUS"
    FROM admin_supply_mng WHERE objid::text = $1`,
    [objid]
  );

  const chargers = await queryRows(
    `SELECT objid AS "OBJID",
      charger_type AS "CHARGER_TYPE",
      charger_name AS "CHARGER_NAME",
      phone AS "PHONE",
      tel AS "TEL",
      fax AS "FAX",
      email AS "EMAIL"
    FROM supply_charger_mng
    WHERE supply_objid = $1
    ORDER BY regdate NULLS LAST, objid`,
    [objid]
  );

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