import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";

// 고객사 관리 (admin/oemMngPagingList.do 대응)
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 conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.oem_name) {
    conditions.push(`O.oem_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.oem_name);
  }
  if (body.status) {
    conditions.push(`LOWER(COALESCE(O.status, 'active')) = LOWER($${idx++})`);
    params.push(body.status);
  }

  const where = conditions.join(" AND ");

  const sql = `
    SELECT O.objid::text AS "OBJID",
      O.oem_code AS "OEM_CODE",
      O.oem_name AS "OEM_NAME",
      O.writer AS "WRITER",
      TO_CHAR(O.regdate, 'YYYY-MM-DD') AS "REGDATE",
      O.status AS "STATUS",
      CASE WHEN UPPER(COALESCE(O.status,'')) = 'ACTIVE' THEN '활성화'
           WHEN UPPER(COALESCE(O.status,'')) = 'INACTIVE' THEN '비활성화'
           ELSE O.status END AS "STATUS_STR"
    FROM oem_mng O
    WHERE ${where}
    ORDER BY O.regdate DESC NULLS LAST
  `;

  try {
    const rows = await queryRows(sql, params);
    return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
  } catch (error) {
    console.error("고객사 관리 조회 오류:", error);
    return NextResponse.json({ success: false, message: "처리 중 오류가 발생했습니다." }, { status: 500 });
  }
}
