import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoUser } from "@/lib/momo-guard";

export async function POST(req: NextRequest) {
  const r = await requireMomoUser();
  if (r instanceof NextResponse) return r;

  const body = await req.json().catch(() => ({}));
  const { dateFrom, dateTo, status, customerObjid, keyword } = body as {
    dateFrom?: string; dateTo?: string; status?: string; customerObjid?: string; keyword?: string;
  };

  const conditions: string[] = ["COALESCE(O.is_del,'N') != 'Y'"];
  const params: unknown[] = [];
  let i = 1;

  if (r.user.role === "USER") {
    conditions.push(`O.customer_objid = $${i++}`);
    params.push(r.user.objid);
  } else if (customerObjid) {
    conditions.push(`O.customer_objid = $${i++}`);
    params.push(customerObjid);
  }

  if (status) {
    conditions.push(`O.status = $${i++}`);
    params.push(status);
  }
  if (dateFrom) {
    conditions.push(`O.order_date >= $${i++}::date`);
    params.push(dateFrom);
  }
  if (dateTo) {
    conditions.push(`O.order_date <= $${i++}::date`);
    params.push(dateTo);
  }
  if (keyword && keyword.trim()) {
    conditions.push(`(O.order_no ILIKE '%' || $${i} || '%' OR U.user_name ILIKE '%' || $${i} || '%' OR U.email ILIKE '%' || $${i} || '%')`);
    params.push(keyword.trim());
    i++;
  }

  const rows = await queryRows(
    `SELECT
       O.objid           AS "OBJID",
       O.order_no        AS "ORDER_NO",
       TO_CHAR(O.order_date, 'YYYY-MM-DD') AS "ORDER_DATE",
       O.customer_objid  AS "CUSTOMER_OBJID",
       U.user_name    AS "COMPANY_NAME",
       U.email           AS "EMAIL",
       O.status          AS "STATUS",
       O.total_supply    AS "TOTAL_SUPPLY",
       O.total_vat       AS "TOTAL_VAT",
       O.total_amount    AS "TOTAL_AMOUNT",
       O.total_taxfree   AS "TOTAL_TAXFREE",
       O.total_taxable   AS "TOTAL_TAXABLE",
       O.invoice_no      AS "INVOICE_NO",
       TO_CHAR(O.invoice_date, 'YYYY-MM-DD') AS "INVOICE_DATE",
       O.paid_amount     AS "PAID_AMOUNT",
       TO_CHAR(O.approve_date, 'YYYY-MM-DD HH24:MI') AS "APPROVE_DATE",
       O.memo            AS "MEMO"
     FROM momo_orders O
     LEFT JOIN user_info U ON U.user_id = O.customer_objid
     WHERE ${conditions.join(" AND ")}
     ORDER BY O.order_date DESC, O.regdate DESC
     LIMIT 500`,
    params
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
