/**
 * Dashboard WhatsApp Conversations API
 * GET /api/dashboard/whatsapp-conversations
 *
 * Lists WhatsApp conversations for the user's organization.
 * Requires user authentication via auth().
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveDataOwnerId } from "@/lib/utils/organization-data";
import { listConversations } from "@/lib/services/whatsapp-conversations.service";
import { ConversationListQuerySchema } from "@/lib/validators/whatsapp-ai.validator";
import { logger } from "@/lib/logger";

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { error: "Unauthorized", message: "Authentication required" },
        { status: 401 },
      );
    }

    const { organizationId } = await getEffectiveDataOwnerId(user.userId);
    if (!organizationId) {
      return NextResponse.json(
        {
          error: "No organization found",
          message: "User must belong to an organization",
        },
        { status: 403 },
      );
    }

    const searchParams = request.nextUrl.searchParams;
    const language = searchParams.get("language") as "en" | "ar" | null;
    const status = searchParams.get("status") as
      | "active"
      | "closed"
      | "archived"
      | null;
    const limit = searchParams.get("limit");
    const offset = searchParams.get("offset");

    // Validate query parameters — always override organizationId with resolved value for security
    // Only pass limit/offset when explicitly provided, otherwise let schema defaults apply
    const validation = ConversationListQuerySchema.safeParse({
      organizationId,
      language,
      status,
      ...(limit != null && { limit }),
      ...(offset != null && { offset }),
    });

    if (!validation.success) {
      return NextResponse.json(
        { error: "Invalid request", details: validation.error.errors },
        { status: 400 },
      );
    }

    const params = validation.data;

    const result = await listConversations(params);

    logger.info("Dashboard conversations listed", {
      userId: user.userId,
      organizationId,
      count: result.conversations.length,
      total: result.total,
    });

    return NextResponse.json({
      success: true,
      data: {
        conversations: result.conversations,
        total: result.total,
        limit: params.limit,
        offset: params.offset,
      },
    });
  } catch (error) {
    logger.error("Dashboard conversations list error", { error });

    return NextResponse.json(
      {
        error: "Internal server error",
        message:
          error instanceof Error
            ? error.message
            : "Failed to list conversations",
      },
      { status: 500 },
    );
  }
}
