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

// 기술자료 카테고리 관리 (admin/specDataCategoryMngList.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.category_name) {
    conditions.push(`S.category_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.category_name);
  }
  if (body.category_type) {
    conditions.push(`S.category_type = $${idx++}`);
    params.push(body.category_type);
  }
  if (body.status) {
    conditions.push(`LOWER(COALESCE(S.status, 'active')) = LOWER($${idx++})`);
    params.push(body.status);
  }

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

  const sql = `
    SELECT S.objid::text AS "OBJID",
      S.parent_objid::text AS "PARENT_OBJID",
      S.category_type AS "CATEGORY_TYPE",
      S.category_name AS "CATEGORY_NAME",
      S.spec_no AS "SPEC_NO",
      S.spec_input_type AS "SPEC_INPUT_TYPE",
      S.doc_no_rule AS "DOC_NO_RULE",
      S.seq AS "SEQ",
      S.use_car AS "USE_CAR",
      S.use_product AS "USE_PRODUCT",
      S.use_product_group AS "USE_PRODUCT_GROUP",
      S.use_revision AS "USE_REVISION",
      S.use_doc_link AS "USE_DOC_LINK",
      S.use_compatition_car AS "USE_COMPATITION_CAR",
      S.use_manufacturer AS "USE_MANUFACTURER",
      S.use_participation_date AS "USE_PARTICIPATION_DATE",
      S.writer AS "WRITER",
      TO_CHAR(S.regdate, 'YYYY-MM-DD') AS "REGDATE",
      S.status AS "STATUS",
      CASE WHEN UPPER(COALESCE(S.status,'')) = 'ACTIVE' THEN '활성화'
           WHEN UPPER(COALESCE(S.status,'')) = 'INACTIVE' THEN '비활성화'
           ELSE S.status END AS "STATUS_STR"
    FROM standard_doc_category S
    WHERE ${where}
    ORDER BY S.seq ASC NULLS LAST, S.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 });
  }
}
