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

// CS 메인 목록 (as_mng 기반 — customerServiceList.jsp 대응)
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.year) {
    conditions.push(`A.year = $${idx++}`);
    params.push(body.year);
  }
  if (body.customer_name) {
    conditions.push(`COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = A.custcd LIMIT 1), A.company_name) LIKE '%' || $${idx++} || '%'`);
    params.push(body.customer_name);
  }

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

  const rows = await queryRows(
    `SELECT A.objid::text AS "OBJID",
       A.as_no AS "CS_NO",
       COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = A.custcd LIMIT 1), A.company_name) AS "CUSTOMER_NAME",
       COALESCE(A.product_name, (SELECT code_name FROM comm_code WHERE code_id = A.product_code LIMIT 1)) AS "PRODUCT_NAME",
       A.release_date AS "RECEIPT_DATE",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = A.rec_type LIMIT 1), '') AS "CS_TYPE_NAME",
       A.problem_contents AS "DESCRIPTION",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = A.status_cd LIMIT 1), A.status_cd) AS "STATUS_NAME",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = A.writer LIMIT 1), '') AS "CHARGER_NAME",
       A.plan_date AS "COMPLETE_DATE"
     FROM as_mng A
     WHERE ${where}
     ORDER BY A.reg_date DESC NULLS LAST, A.as_no DESC
`,
    params
  );

  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
