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

// 재질 관리 (admin/getMaterialMngList.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.material_name) {
    conditions.push(`M.material_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.material_name);
  }
  if (body.status) {
    conditions.push(`LOWER(COALESCE(M.status, 'active')) = LOWER($${idx++})`);
    params.push(body.status);
  }

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

  const sql = `
    SELECT M.objid::text AS "OBJID",
      M.material_name AS "MATERIAL_NAME",
      M.writer AS "WRITER",
      TO_CHAR(M.regdate, 'YYYY-MM-DD') AS "REGDATE",
      M.status AS "STATUS",
      CASE WHEN UPPER(COALESCE(M.status,'')) = 'ACTIVE' THEN '활성화'
           WHEN UPPER(COALESCE(M.status,'')) = 'INACTIVE' THEN '비활성화'
           ELSE M.status END AS "STATUS_STR"
    FROM material_mng M
    WHERE ${where}
    ORDER BY M.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 });
  }
}
