import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getOperatorEarnings } from "@/lib/marketplace-billing";
import { logger } from "@/lib/logger";

/**
 * GET /api/dashboard/operator/earnings?period=30
 *
 * Returns earnings summary for the authenticated operator.
 * Query params:
 *   - period: number of days to aggregate (default 30, max 365)
 */
export async function GET(request: Request) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Parse period from query params
    const url = new URL(request.url);
    const periodParam = url.searchParams.get("period");
    let periodDays = 30;
    if (periodParam) {
      const parsed = parseInt(periodParam, 10);
      if (!Number.isNaN(parsed) && parsed > 0 && parsed <= 365) {
        periodDays = parsed;
      }
    }

    const earnings = await getOperatorEarnings(session.user.id, periodDays);

    return NextResponse.json(earnings);
  } catch (error) {
    logger.error({ error }, "operator_earnings_get_failed");
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}
