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

// 템플릿 관리 (admin/templateList.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.title) {
    conditions.push(`T.title LIKE '%' || $${idx++} || '%'`);
    params.push(body.title);
  }
  if (body.template_code) {
    conditions.push(`T.template_code LIKE '%' || $${idx++} || '%'`);
    params.push(body.template_code);
  }
  if (body.status) {
    conditions.push(`LOWER(COALESCE(T.status, 'active')) = LOWER($${idx++})`);
    params.push(body.status);
  }

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

  const sql = `
    SELECT T.objid::text AS "OBJID",
      T.template_code AS "TEMPLATE_CODE",
      T.template_code_detail AS "TEMPLATE_CODE_DETAIL",
      T.title AS "TITLE",
      TO_CHAR(T.reg_date, 'YYYY-MM-DD') AS "REG_DATE",
      T.status AS "STATUS",
      CASE WHEN UPPER(COALESCE(T.status,'')) = 'ACTIVE' THEN '활성화'
           WHEN UPPER(COALESCE(T.status,'')) = 'INACTIVE' THEN '비활성화'
           ELSE T.status END AS "STATUS_STR"
    FROM template_mng T
    WHERE ${where}
    ORDER BY T.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 });
  }
}
