/**
 * GET /api/conversations
 *
 * Returns WhatsApp conversations for the dashboard.
 * All data access goes through Convex. No Prisma fallback.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedEmail } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { convexQuery } from "@/lib/convex-client";
import { getErrorMessage } from "@/lib/errors";

export const dynamic = "force-dynamic";

interface ConvexUser {
  _id: string;
  prismaId?: string;
  appUserId?: string;
  email: string;
}

export async function GET(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

    if (!userEmail) {
      logger.warn("Unauthorized conversations request");
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Get user from Convex
    const convexUser = await convexQuery<ConvexUser>(
      "auth/queries:getUserByEmail",
      { email: userEmail },
    );

    if (!convexUser) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    const userId =
      convexUser.prismaId || convexUser.appUserId || convexUser._id;

    const limitParam = request.nextUrl.searchParams.get("limit");
    const limit = limitParam
      ? Math.min(100, Math.max(1, parseInt(limitParam, 10)))
      : 50;
    const status = request.nextUrl.searchParams.get("status");

    // Fetch conversations from Convex
    const conversations = await convexQuery<unknown[]>(
      "conversations/queries:getConversations",
      {
        userId,
        ...(status && status !== "all" ? { status } : {}),
        limit,
      },
    );

    if (conversations) {
      logger.info("Conversations retrieved", {
        userEmail,
        count: conversations.length,
      });

      return NextResponse.json({
        conversations,
        total: conversations.length,
        limit,
      });
    }

    // Convex returned null — return empty
    return NextResponse.json({
      conversations: [],
      total: 0,
      limit,
    });
  } catch (error) {
    logger.error("Conversations error", {
      error: getErrorMessage(error),
    });

    return NextResponse.json(
      { error: "Failed to retrieve conversations" },
      { status: 500 },
    );
  }
}
