/**
 * Reviews API
 * GET - List reviews with filtering
 * POST - Create a new review manually
 *
 * All data access goes through Convex. No Prisma fallback.
 */

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 { CreateReviewSchema } from "@/lib/validators/reviews.validator";
import { logger } from "@/lib/logger";
import { convexQuery, convexMutation } from "@/lib/convex-client";
const log = logger.scope("ReviewsAPI");

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 platform = request.nextUrl.searchParams.get("platform") ?? undefined;
    const limitParam = request.nextUrl.searchParams.get("limit");
    const limit = limitParam ? parseInt(limitParam, 10) : 50;

    const result = await convexQuery("reviews/queries:getReviews", {
      userId: effectiveUserId,
      platform,
      limit,
    });

    return NextResponse.json({ reviews: result ?? [], success: true });
  } catch (error) {
    log.error("Failed to list reviews", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function POST(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 body = await request.json();
    const parsed = CreateReviewSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { success: false, error: parsed.error.flatten() },
        { status: 400 },
      );
    }

    const reviewId = await convexMutation("reviews/mutations:createReview", {
      userId: effectiveUserId,
      customerName: parsed.data.customerName,
      customerEmail: parsed.data.customerEmail ?? undefined,
      customerPhone: parsed.data.customerPhone ?? undefined,
      platform: parsed.data.platform ?? undefined,
      rating: parsed.data.rating,
      title: parsed.data.title ?? undefined,
      content: parsed.data.content ?? undefined,
      language: parsed.data.language ?? undefined,
    });

    if (reviewId !== null) {
      return NextResponse.json(
        { success: true, review: { id: reviewId } },
        { status: 201 },
      );
    }

    return NextResponse.json(
      { success: false, error: "Failed to create review" },
      { status: 503 },
    );
  } catch (error) {
    log.error("Failed to create review", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
