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

// 차종 관리 (admin/getCarMngList.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.car_name) {
    conditions.push(`C.car_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.car_name);
  }
  if (body.car_code) {
    conditions.push(`C.car_code LIKE '%' || $${idx++} || '%'`);
    params.push(body.car_code);
  }
  if (body.status) {
    conditions.push(`LOWER(COALESCE(C.status, 'active')) = LOWER($${idx++})`);
    params.push(body.status);
  }

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

  const sql = `
    SELECT C.objid::text AS "OBJID",
      C.car_code AS "CAR_CODE",
      C.model_code AS "MODEL_CODE",
      C.car_name AS "CAR_NAME",
      C.description AS "DESCRIPTION",
      C.oem_objid::text AS "OEM_OBJID",
      (SELECT oem_name FROM oem_mng O WHERE O.objid = C.oem_objid) AS "OEM_NAME",
      C.writer AS "WRITER",
      TO_CHAR(C.regdate, 'YYYY-MM-DD') AS "REGDATE",
      C.status AS "STATUS",
      CASE WHEN UPPER(COALESCE(C.status,'')) = 'ACTIVE' THEN '활성화'
           WHEN UPPER(COALESCE(C.status,'')) = 'INACTIVE' THEN '비활성화'
           ELSE C.status END AS "STATUS_STR"
    FROM car_mng C
    WHERE ${where}
    ORDER BY C.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 });
  }
}
