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 { year, month } = await req.json();
  const y = Number(year) || new Date().getFullYear();
  const m = Number(month) || new Date().getMonth() + 1;

  const rows = await queryRows(
    `SELECT
       U.user_name AS "COMPANY_NAME",
       COALESCE(SUM(O.total_taxfree), 0) AS "TAX_FREE",
       COALESCE(SUM(O.total_taxable), 0) AS "TAXABLE",
       COALESCE(SUM(O.total_amount), 0) AS "TOTAL"
     FROM momo_orders O
     LEFT JOIN user_info U ON U.user_id = O.customer_objid
     WHERE EXTRACT(YEAR FROM O.order_date) = $1
       AND EXTRACT(MONTH FROM O.order_date) = $2
       AND O.status IN ('APPROVED', 'INVOICED', 'PAID')
       AND COALESCE(O.is_del,'N') != 'Y'
     GROUP BY U.user_name
     ORDER BY "TOTAL" DESC`,
    [y, m]
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
