// 거래처(회원) 목록 — 관리자 전용
import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;

  const body = await req.json().catch(() => ({}));
  const { keyword, status } = body as { keyword?: string; status?: string };

  // 거래처 = 관리자 아닌 사용자 모두 (user_type='U' 또는 legacy 'C')
  const conditions: string[] = ["COALESCE(user_type, '') NOT IN ('A')"];
  const params: unknown[] = [];
  let i = 1;
  if (keyword) {
    conditions.push(`(user_id ILIKE '%' || $${i} || '%' OR user_name ILIKE '%' || $${i} || '%' OR email ILIKE '%' || $${i} || '%')`);
    params.push(keyword);
    i++;
  }
  if (status) {
    conditions.push(`status = $${i++}`);
    params.push(status);
  }

  const rows = await queryRows(
    `SELECT
       user_id        AS "USER_ID",
       user_name      AS "USER_NAME",
       email          AS "EMAIL",
       cell_phone     AS "CELL_PHONE",
       biz_no         AS "BIZ_NO",
       ceo_name       AS "CEO_NAME",
       address        AS "ADDRESS",
       status         AS "STATUS",
       COALESCE(unlimited_qty, 'N') AS "UNLIMITED_QTY",
       COALESCE(view_hidden, 'N')   AS "VIEW_HIDDEN",
       TO_CHAR(regdate, 'YYYY-MM-DD') AS "REGDATE"
     FROM user_info
     WHERE ${conditions.join(" AND ")}
     ORDER BY regdate DESC
     LIMIT 500`,
    params
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
