/**
 * Conversations API
 *
 * GET - Get conversations with pagination and filtering
 */

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 { conversationTrackerService } from "@/lib/services/conversation-tracker.service";
import { logger } from "@/lib/logger";

const scopedLogger = logger.scope("ConversationsAPI");

/**
 * GET /api/dashboard/conversations
 * Returns conversations with pagination and filtering
 *
 * Query Parameters:
 * - platform: Filter by platform (whatsapp, voice, social)
 * - status: Filter by status (open, resolved, archived)
 * - limit: Number of results per page (default: 50, max: 100)
 * - offset: Number of results to skip (default: 0)
 */
export async function GET(request: NextRequest) {
  try {
    // Authenticate user
    const user = await getAuthenticatedUser(request, auth);

    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    // Parse query parameters
    const searchParams = request.nextUrl.searchParams;
    const platform = searchParams.get("platform") || undefined;
    const status = searchParams.get("status") || undefined;
    const limitParam = searchParams.get("limit");
    const offsetParam = searchParams.get("offset");

    // Validate and parse limit
    let limit = 50; // Default
    if (limitParam) {
      const parsedLimit = parseInt(limitParam, 10);
      if (isNaN(parsedLimit) || parsedLimit < 1) {
        return NextResponse.json(
          { success: false, error: "Limit must be a positive number" },
          { status: 400 },
        );
      }
      limit = Math.min(parsedLimit, 100); // Cap at 100
    }

    // Validate and parse offset
    let offset = 0; // Default
    if (offsetParam) {
      const parsedOffset = parseInt(offsetParam, 10);
      if (isNaN(parsedOffset) || parsedOffset < 0) {
        return NextResponse.json(
          { success: false, error: "Offset must be a non-negative number" },
          { status: 400 },
        );
      }
      offset = parsedOffset;
    }

    // Validate platform if provided
    if (platform && !["whatsapp", "voice", "social"].includes(platform)) {
      return NextResponse.json(
        {
          success: false,
          error: "Invalid platform. Must be: whatsapp, voice, or social",
        },
        { status: 400 },
      );
    }

    // Validate status if provided
    if (status && !["open", "resolved", "archived"].includes(status)) {
      return NextResponse.json(
        {
          success: false,
          error: "Invalid status. Must be: open, resolved, or archived",
        },
        { status: 400 },
      );
    }

    // Get effective owner ID (for org members, this returns the org owner's ID)
    const effectiveUserId = await getEffectiveOwnerId(user.userId);

    // Get conversations with filters - use effective owner ID to see all org data
    const conversations = await conversationTrackerService.getUserConversations(
      effectiveUserId,
      {
        platform,
        status,
        limit,
        offset,
      },
    );

    scopedLogger.info("Conversations retrieved", {
      userId: user.userId,
      count: conversations.length,
      platform,
      status,
      limit,
      offset,
    });

    return NextResponse.json({
      success: true,
      conversations,
      pagination: {
        limit,
        offset,
        count: conversations.length,
        hasMore: conversations.length === limit, // If we got full limit, there might be more
      },
      filters: {
        platform: platform || "all",
        status: status || "all",
      },
    });
  } catch (error) {
    scopedLogger.error("Failed to get conversations", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
