/**
 * Review Requests API
 * GET  - List review requests for the user
 * POST - Create a review request
 */

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 {
  createReviewRequest,
  listReviewRequests,
} from "@/lib/services/reviews.service";
import { CreateReviewRequestSchema } from "@/lib/validators/reviews.validator";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

const log = logger.scope("ReviewRequestsAPI");

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);

    if (getDataSource("reviews") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const { searchParams } = new URL(request.url);
        const limit = parseInt(searchParams.get("limit") ?? "20", 10);
        const status = searchParams.get("status") ?? undefined;
        const result = await convexQuery("reviews/queries:getReviewRequests", {
          userId: effectiveUserId,
          status,
          limit,
        });
        if (result !== null) {
          return NextResponse.json({ success: true, requests: result });
        }
      } catch {
        // Fall through to Prisma
      }
    }

    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get("page") ?? "1", 10);
    const limit = parseInt(searchParams.get("limit") ?? "20", 10);

    const result = await listReviewRequests(effectiveUserId, page, limit);
    return NextResponse.json({ success: true, ...result });
  } catch (error) {
    log.error("Failed to list review requests", 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 = CreateReviewRequestSchema.safeParse(body);

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

    if (getDataSource("reviews") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        const result = await convexMutation(
          "reviews/mutations:createReviewRequest",
          {
            userId: effectiveUserId,
            customerName: parsed.data.customerName,
            customerEmail: parsed.data.customerEmail ?? undefined,
            customerPhone: parsed.data.customerPhone ?? undefined,
            channel: parsed.data.channel ?? undefined,
            message: parsed.data.message ?? undefined,
            language: parsed.data.language ?? undefined,
            bookingId: parsed.data.bookingId ?? undefined,
          },
        );
        if (result !== null) {
          return NextResponse.json(
            { success: true, reviewRequest: result },
            { status: 201 },
          );
        }
      } catch {
        // Fall through to Prisma
      }
    }

    const reviewRequest = await createReviewRequest(
      effectiveUserId,
      parsed.data,
    );
    return NextResponse.json({ success: true, reviewRequest }, { status: 201 });
  } catch (error) {
    log.error("Failed to create review request", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
