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

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  const { dateFrom, dateTo } = await req.json();
  const rows = await queryRows(
    `SELECT TO_CHAR(O.order_date,'YYYY-MM-DD') AS "DAY",
            COUNT(*) AS "ORDER_CNT",
            COALESCE(SUM(O.total_amount),0) AS "TOTAL",
            COALESCE(SUM(O.total_taxfree),0) AS "TAX_FREE",
            COALESCE(SUM(O.total_taxable),0) AS "TAXABLE"
     FROM momo_orders O
     WHERE O.order_date BETWEEN $1::date AND $2::date
       AND O.status IN ('APPROVED','PAID','INVOICED')
       AND COALESCE(O.is_del,'N') != 'Y'
     GROUP BY O.order_date ORDER BY O.order_date ASC`,
    [dateFrom, dateTo]
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
