import { createAdminClient } from "@/lib/supabase/server"; import { auth } from "@clerk/nextjs/server"; import { NextResponse } from "next/server"; /** * GET /api/usage * Returns current month's usage counts and estimated cost. */ export async function GET() { try { const { userId } = await auth(); if (!userId) return NextResponse.json({ error: "Unauthenticated" }, { status: 401 }); const supabase = await createAdminClient(); const { data: member } = await supabase .from("organisation_members") .select("organisation_id") .eq("user_id", userId) .single(); if (!member) return NextResponse.json({ error: "No organisation" }, { status: 404 }); const orgId = member.organisation_id; const now = new Date(); const monthStart = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-01`; // Invoice count const { count: invoices } = await supabase .from("invoices") .select("*", { count: "exact", head: true }) .eq("organisation_id", orgId) .gte("created_at", monthStart); // Employee count const { count: employees } = await supabase .from("employees") .select("*", { count: "exact", head: true }) .eq("organisation_id", orgId); // Payroll runs this month const { count: payrollRuns } = await supabase .from("payroll_runs") .select("*", { count: "exact", head: true }) .eq("organisation_id", orgId) .gte("created_at", monthStart); // Expenses this month const { count: expenses } = await supabase .from("expenses") .select("*", { count: "exact", head: true }) .eq("organisation_id", orgId) .gte("created_at", monthStart); // Leave requests this month const { count: leaveRequests } = await supabase .from("leave_requests") .select("*", { count: "exact", head: true }) .eq("organisation_id", orgId) .gte("created_at", monthStart); const invoiceCount = invoices || 0; const employeeCount = employees || 0; const payrollCount = payrollRuns || 0; const expenseCount = expenses || 0; const leaveCount = leaveRequests || 0; // Estimated cost const estimatedCost = invoiceCount * 50 + // $0.50 × invoices employeeCount * 100 + // $1.00 × employees payrollCount * 300 + // $3.00 × payroll runs expenseCount * 25 + // $0.25 × expenses leaveCount * 50; // $0.50 × leave requests return NextResponse.json({ invoices: invoiceCount, employees: employeeCount, payrollRuns: payrollCount, estimatedCost, }); } catch { return NextResponse.json({ error: "Failed to fetch usage" }, { status: 500 }); } }