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

// 제품 관리 (admin/getProductMngList.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.product_name) {
    conditions.push(`P.product_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.product_name);
  }
  if (body.product_code) {
    conditions.push(`P.product_code LIKE '%' || $${idx++} || '%'`);
    params.push(body.product_code);
  }
  if (body.status) {
    conditions.push(`LOWER(COALESCE(P.status, 'active')) = LOWER($${idx++})`);
    params.push(body.status);
  }

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

  const sql = `
    SELECT P.objid::text AS "OBJID",
      P.product_code AS "PRODUCT_CODE",
      P.product_name AS "PRODUCT_NAME",
      P.product_desc AS "PRODUCT_DESC",
      P.product_group_objid::text AS "PRODUCT_GROUP_OBJID",
      (SELECT product_group_name FROM product_group_mng G WHERE G.objid = P.product_group_objid) AS "PRODUCT_GROUP_NAME",
      P.writer AS "WRITER",
      TO_CHAR(P.regdate, 'YYYY-MM-DD') AS "REGDATE",
      P.status AS "STATUS",
      CASE WHEN UPPER(COALESCE(P.status,'')) = 'ACTIVE' THEN '활성화'
           WHEN UPPER(COALESCE(P.status,'')) = 'INACTIVE' THEN '비활성화'
           ELSE P.status END AS "STATUS_STR"
    FROM product_mng P
    WHERE ${where}
    ORDER BY P.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 });
  }
}
