// 월간 거래처×일자 피벗 통계 — 면세/과세 분리
// 응답: { dates: ["2026-02-04", ...], rows: [{ COMPANY_NAME, BY_DAY: {date: {TAXFREE, TAXABLE}}, TOTAL_TAXFREE, TOTAL_TAXABLE }], totalsByDay, grandTotal }
import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";

interface DayCell { TAXFREE: number; TAXABLE: number }
interface Row { COMPANY_NAME: string; CUSTOMER_OBJID: string; BY_DAY: Record<string, DayCell>; TOTAL_TAXFREE: number; TOTAL_TAXABLE: number }

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

  const { year, month } = await req.json().catch(() => ({}));
  const y = Number(year) || new Date().getFullYear();
  const m = Number(month) || new Date().getMonth() + 1;

  // 거래처별 + 일자별 면세/과세 합계 (출고완료 이상만)
  const rows = await queryRows<{
    DAY: string; CUSTOMER_OBJID: string; COMPANY_NAME: string;
    TAXFREE: number; TAXABLE: number;
  }>(
    `SELECT
       TO_CHAR(O.order_date, 'YYYY-MM-DD') AS "DAY",
       O.customer_objid                    AS "CUSTOMER_OBJID",
       COALESCE(U.user_name, O.customer_objid) AS "COMPANY_NAME",
       COALESCE(SUM(O.total_taxfree), 0)   AS "TAXFREE",
       COALESCE(SUM(O.total_taxable), 0)   AS "TAXABLE"
     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','SHIPPED','PAID','INVOICED')
       AND COALESCE(O.is_del, 'N') != 'Y'
     GROUP BY 1, 2, 3
     ORDER BY "COMPANY_NAME"`,
    [y, m]
  );

  // 거래처별로 묶기
  const byCust = new Map<string, Row>();
  const dateSet = new Set<string>();
  for (const r of rows) {
    dateSet.add(r.DAY);
    if (!byCust.has(r.CUSTOMER_OBJID)) {
      byCust.set(r.CUSTOMER_OBJID, {
        COMPANY_NAME: r.COMPANY_NAME,
        CUSTOMER_OBJID: r.CUSTOMER_OBJID,
        BY_DAY: {},
        TOTAL_TAXFREE: 0,
        TOTAL_TAXABLE: 0,
      });
    }
    const row = byCust.get(r.CUSTOMER_OBJID)!;
    row.BY_DAY[r.DAY] = { TAXFREE: Number(r.TAXFREE), TAXABLE: Number(r.TAXABLE) };
    row.TOTAL_TAXFREE += Number(r.TAXFREE);
    row.TOTAL_TAXABLE += Number(r.TAXABLE);
  }

  const dates = Array.from(dateSet).sort();
  const resultRows = Array.from(byCust.values()).sort((a, b) => b.TOTAL_TAXFREE + b.TOTAL_TAXABLE - (a.TOTAL_TAXFREE + a.TOTAL_TAXABLE));

  // 일자별 총합 + 전체 총합
  const totalsByDay: Record<string, DayCell> = {};
  let grandFree = 0, grandTaxable = 0;
  for (const d of dates) {
    let f = 0, t = 0;
    for (const r of resultRows) {
      const c = r.BY_DAY[d];
      if (c) { f += c.TAXFREE; t += c.TAXABLE; }
    }
    totalsByDay[d] = { TAXFREE: f, TAXABLE: t };
    grandFree += f;
    grandTaxable += t;
  }

  return NextResponse.json({
    success: true,
    year: y,
    month: m,
    dates,
    rows: resultRows,
    totalsByDay,
    grandTotal: { TAXFREE: grandFree, TAXABLE: grandTaxable, TOTAL: grandFree + grandTaxable },
  });
}
