/**
 * Testimonials (Featured Reviews) API
 * GET  - List ALL reviews for the user (featured + unfeatured)
 * POST - Toggle a review's featured status
 * PUT  - Reorder featured reviews
 *
 * Database: Convex only — 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 {
  ToggleFeaturedSchema,
  ReorderFeaturedSchema,
} from "@/lib/validators/reviews.validator";
import { logger } from "@/lib/logger";

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

/** Shape returned by Convex getReviews query */
type ConvexReview = {
  _id: string;
  _creationTime?: number;
  customerName: string;
  rating: number;
  content?: string | null;
  isFeatured?: boolean;
  featuredOrder?: number;
  sortOrder?: number;
  createdAt: number;
  [key: string]: unknown;
};

/** Map a Convex review document to the client-facing shape (id, not _id) */
function toClientReview(r: ConvexReview) {
  const { _id, _creationTime, ...rest } = r;
  return {
    ...rest,
    id: _id,
    isFeatured: r.isFeatured ?? false,
    sortOrder: r.featuredOrder ?? 0,
    createdAt: new Date(r.createdAt).toISOString(),
  };
}

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 { convexQuery } = await import("@/lib/convex-client");
    const reviews = await convexQuery<ConvexReview[]>(
      "reviews/queries:getReviews",
      { userId: effectiveUserId },
    );

    if (!reviews) {
      return NextResponse.json({ success: true, testimonials: [] });
    }

    // Map _id → id, then sort: featured first (by featuredOrder), unfeatured by createdAt desc
    const allReviews = reviews.map(toClientReview).sort((a, b) => {
      if (a.isFeatured && !b.isFeatured) return -1;
      if (!a.isFeatured && b.isFeatured) return 1;
      if (a.isFeatured && b.isFeatured) {
        return (a.sortOrder ?? 0) - (b.sortOrder ?? 0);
      }
      return (
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      );
    });

    return NextResponse.json({ success: true, testimonials: allReviews });
  } 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 = ToggleFeaturedSchema.safeParse(body);

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

    const { convexMutation } = await import("@/lib/convex-client");
    const result = await convexMutation("reviews/mutations:updateReview", {
      userId: effectiveUserId,
      reviewId: parsed.data.reviewId,
      isFeatured: parsed.data.featured,
    });

    if (result === null) {
      log.error("Convex updateReview returned null", {
        reviewId: parsed.data.reviewId,
      });
      return NextResponse.json(
        { success: false, error: "Failed to update review" },
        { status: 500 },
      );
    }

    return NextResponse.json({ success: true, review: { id: result } });
  } catch (error) {
    log.error("Failed to toggle featured review", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function PUT(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 = ReorderFeaturedSchema.safeParse(body);

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

    const { convexMutation } = await import("@/lib/convex-client");
    const result = await convexMutation(
      "reviews/mutations:reorderFeaturedReviews",
      {
        userId: effectiveUserId,
        orderedIds: parsed.data.orderedIds,
      },
    );

    if (result === null) {
      log.error("Convex reorderFeaturedReviews returned null");
      return NextResponse.json(
        { success: false, error: "Failed to reorder reviews" },
        { status: 500 },
      );
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    log.error("Failed to reorder featured reviews", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
