/**
 * Review Stats API
 * GET - Get review statistics and request stats
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { convexQuery } from "@/lib/convex-client";
import { logger } from "@/lib/logger";
const log = logger.scope("ReviewStatsAPI");

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerId(user.userId);

    const reviewStats = await convexQuery("reviews/queries:getReviewStats", {
      userId: effectiveUserId,
    });

    return NextResponse.json({
      success: true,
      reviewStats: reviewStats ?? {
        total: 0,
        averageRating: 0,
        distribution: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 },
        responseRate: 0,
        byPlatform: {},
        recentCount: 0,
      },
    });
  } catch (error) {
    log.error("Failed to get review stats", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
