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

// 차량옵션(사양) 관리 (admin/getCarOptionMngList.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.option_name) {
    conditions.push(`O.option_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.option_name);
  }
  if (body.option_no) {
    conditions.push(`O.option_no LIKE '%' || $${idx++} || '%'`);
    params.push(body.option_no);
  }
  if (body.option_type) {
    conditions.push(`O.option_type = $${idx++}`);
    params.push(body.option_type);
  }
  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 AS "OBJID",
      O.option_no AS "OPTION_NO",
      O.option_name AS "OPTION_NAME",
      O.option_name_eng AS "OPTION_NAME_ENG",
      O.std_code AS "STD_CODE",
      O.option_type AS "OPTION_TYPE",
      O.category AS "CATEGORY",
      O.parent_objid AS "PARENT_OBJID",
      O.price AS "PRICE",
      O.writer AS "WRITER",
      O.reg_date AS "REG_DATE",
      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 option_mng O
    WHERE ${where}
    ORDER BY O.reg_date 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 });
  }
}
