// 지사별 매출/마진/본사 수수료(20%) 집계
// statement_branch 컬럼이 user_info(거래처) 에 박혀있어 그 값으로 그룹핑.
// 본사(HQ) 는 수수료 0, 지사(KIMPO 등) 는 순수 마진의 20% 가 본사 수수료.
import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";

const HQ_FEE_RATE = 0.2;  // 본사 수수료 20%

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  const body = await req.json().catch(() => ({}));
  const y = Number(body.year) || new Date().getFullYear();
  const m = Number(body.month) || new Date().getMonth() + 1;

  const rows = await queryRows<{ BRANCH: string; REVENUE: string; COST: string; MARGIN: string; CNT: string }>(
    `SELECT
       COALESCE(U.statement_branch, 'HQ')                            AS "BRANCH",
       COALESCE(SUM(OI.supply_amount), 0)                            AS "REVENUE",
       COALESCE(SUM(OI.qty * COALESCE(I.cost_price, 0)), 0)          AS "COST",
       COALESCE(SUM(OI.supply_amount) - SUM(OI.qty * COALESCE(I.cost_price, 0)), 0) AS "MARGIN",
       COUNT(DISTINCT O.objid)                                       AS "CNT"
     FROM momo_orders O
     JOIN momo_order_items OI ON O.objid = OI.order_objid
     LEFT JOIN momo_items I ON OI.item_objid = I.objid
     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','PAID','INVOICED')
       AND COALESCE(O.is_del,'N') != 'Y'
       AND COALESCE(OI.kind, 'ITEM') = 'ITEM'
     GROUP BY COALESCE(U.statement_branch, 'HQ')
     ORDER BY "BRANCH"`,
    [y, m]
  );

  // 지사명 매핑 + 본사 수수료 계산
  const branchNames: Record<string, string> = await (async () => {
    const b = await queryRows<{ CODE: string; NAME: string }>(
      `SELECT code AS "CODE", name AS "NAME" FROM momo_statement_branches WHERE COALESCE(is_del,'N') != 'Y'`
    );
    const m: Record<string, string> = {};
    for (const r of b) m[r.CODE] = r.NAME;
    return m;
  })();

  const result = rows.map((r) => {
    const margin = Number(r.MARGIN);
    const isHQ = r.BRANCH === "HQ";
    const hqFee = isHQ ? 0 : Math.round(margin * HQ_FEE_RATE);
    return {
      BRANCH:        r.BRANCH,
      BRANCH_NAME:   branchNames[r.BRANCH] ?? (r.BRANCH === "HQ" ? "본사" : r.BRANCH),
      REVENUE:       Number(r.REVENUE),
      COST:          Number(r.COST),
      MARGIN:        margin,
      ORDER_CNT:     Number(r.CNT),
      HQ_FEE_RATE:   isHQ ? 0 : HQ_FEE_RATE,
      HQ_FEE_AMOUNT: hqFee,
      NET_TO_BRANCH: margin - hqFee,  // 지사가 가져가는 금액 (수수료 제외)
    };
  });

  return NextResponse.json({ RESULTLIST: result, YEAR: y, MONTH: m });
}
