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;

  // 월간 마진 = 매출(공급가) - 원가(qty × cost_price)
  const rows = await queryRows(
    `SELECT
       I.item_code AS "ITEM_CODE",
       I.item_name AS "ITEM_NAME",
       SUM(OI.qty) AS "QTY",
       SUM(OI.supply_amount) AS "REVENUE",
       SUM(OI.qty * I.cost_price) AS "COST",
       SUM(OI.supply_amount) - SUM(OI.qty * I.cost_price) AS "MARGIN"
     FROM momo_orders O
     JOIN momo_order_items OI ON O.objid = OI.order_objid
     JOIN momo_items I ON OI.item_objid = I.objid
     WHERE EXTRACT(YEAR FROM O.order_date) = $1
       AND EXTRACT(MONTH FROM O.order_date) = $2
       AND O.status IN ('APPROVED','PAID','INVOICED')
       AND COALESCE(O.is_del,'N') != 'Y'
     GROUP BY I.item_code, I.item_name
     ORDER BY "MARGIN" DESC`,
    [y, m]
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
