// 유통기한 임박 알림 — momo_inbounds.expiry_date 기준 N일 이내
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 body = await req.json().catch(() => ({}));
  const days = Number(body.days) || 30;  // 기본 30일 이내

  // 입고건 중 expiry_date 가 있고 today + days 이내인 행. 이미 지난 것(과기) 도 포함.
  const rows = await queryRows(
    `SELECT
       I.objid                                            AS "INBOUND_OBJID",
       I.inbound_no                                       AS "INBOUND_NO",
       TO_CHAR(I.inbound_date, 'YYYY-MM-DD')              AS "INBOUND_DATE",
       TO_CHAR(I.expiry_date, 'YYYY-MM-DD')               AS "EXPIRY_DATE",
       (I.expiry_date - CURRENT_DATE)                     AS "DAYS_LEFT",
       W.wh_name                                          AS "WH_NAME",
       V.supply_name                                      AS "VENDOR_NAME",
       I.completed_by                                     AS "COMPLETED_BY",
       I.memo                                             AS "MEMO",
       I.total_amount                                     AS "TOTAL_AMOUNT"
     FROM momo_inbounds I
     LEFT JOIN momo_warehouses W ON W.objid = I.wh_objid
     LEFT JOIN supply_mng V ON V.objid::text = I.vendor_objid
     WHERE I.expiry_date IS NOT NULL
       AND I.expiry_date <= CURRENT_DATE + ($1 || ' days')::interval
       AND COALESCE(I.is_del,'N') != 'Y'
     ORDER BY I.expiry_date ASC`,
    [days]
  );

  // 분류: 이미 만료 / 7일 이내 임박 / 30일 이내 주의
  const now = new Date();
  const expired = rows.filter((r) => Number(r.DAYS_LEFT) < 0);
  const urgent  = rows.filter((r) => Number(r.DAYS_LEFT) >= 0 && Number(r.DAYS_LEFT) <= 7);
  const soon    = rows.filter((r) => Number(r.DAYS_LEFT) > 7);

  return NextResponse.json({
    RESULTLIST: rows,
    TOTAL_CNT: rows.length,
    EXPIRED_CNT: expired.length,
    URGENT_CNT: urgent.length,
    SOON_CNT: soon.length,
    NOW: now.toISOString().slice(0, 10),
  });
}
