import { NextRequest, NextResponse } from "next/server"; import { getWholesaleSettings, getWholesaleProducts } from "@/actions/wholesale"; import { getWholesaleCustomer } from "@/actions/wholesale-register"; import { getAdminUser } from "@/lib/admin-permissions"; import { svcHeaders } from "@/lib/svc-headers"; export const dynamic = "force-dynamic"; // POST /api/wholesale/price-sheet // Generates an HTML price sheet and enqueues it as a price_sheet notification // for one or more wholesale customers. export async function POST(req: NextRequest) { const adminUser = await getAdminUser(); if (!adminUser) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } if (!adminUser.can_manage_settings && !adminUser.can_manage_products) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } const body = await req.json(); const { customerIds, brandId, subject, customNote } = body as { customerIds: string[]; brandId: string; subject?: string; customNote?: string; }; const effectiveBrandId = adminUser.brand_id ?? brandId ?? null; if (!effectiveBrandId) { return NextResponse.json({ error: "Brand ID required" }, { status: 400 }); } if (adminUser.role === "brand_admin" && adminUser.brand_id !== brandId) { return NextResponse.json({ error: "Not authorized for this brand" }, { status: 403 }); } if (!customerIds?.length || !effectiveBrandId) { return NextResponse.json({ error: "customerIds array and brandId are required" }, { status: 400 }); } const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!; const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY!; // Fetch brand settings for branding + pickup location const settings = await getWholesaleSettings(effectiveBrandId); if (!settings) { return NextResponse.json({ error: "Brand settings not found" }, { status: 404 }); } // Fetch products for this brand const products = await getWholesaleProducts(effectiveBrandId); if (products.length === 0) { return NextResponse.json({ error: "No products found for this brand" }, { status: 404 }); } const brandName = settings.invoice_business_name ?? "Wholesale"; const pickupLocation = settings.pickup_location; const generatedDate = new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }); const emailSubject = subject?.trim() || `${brandName} Wholesale Price Sheet — ${generatedDate}`; const hasCustomNote = Boolean(customNote?.trim()); // Build product rows HTML const productRows = products .filter(p => p.availability === "available") .map(p => { const tiersHtml = p.price_tiers .map(t => { const max = t.max_qty === 0 ? "+" : `-${t.max_qty}`; return `${t.min_qty}${max}: $${Number(t.price).toFixed(2)}`; }) .join(" | "); return `