/**
 * Conversation Statistics API
 * GET: Agent performance metrics (response time, conversion rate, etc.)
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { whatsappConversationsAdapter } from "@/lib/adapters/whatsapp";
import { logger } from "@/lib/logger";

export async function GET(req: NextRequest) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const days = parseInt(searchParams.get("days") || "7");

    const startDate = new Date();
    startDate.setDate(startDate.getDate() - days);

    // Get conversation counts by status
    // Limit to 100 most recent conversations to prevent memory issues
    const conversations = await whatsappConversationsAdapter.findMany({
      where: {
        userId: session.user.id,
        createdAt: { gte: startDate },
      },
      include: {
        messages: true,
      },
    });

    // Calculate metrics
    const totalConversations = conversations.length;
    const activeConversations = conversations.filter(
      (c) => c.status === "active",
    ).length;
    const resolvedConversations = conversations.filter(
      (c) => c.status === "resolved",
    ).length;
    const conversationsWithBooking = conversations.filter(
      (c) => c.bookingId,
    ).length;

    // Calculate average response time (time from first customer message to first AI response)
    let totalResponseTimeMs = 0;
    let responseCount = 0;

    conversations.forEach((conv: any) => {
      const messages = conv.conversation_messages || [];
      const firstCustomerMsg = messages.find(
        (m: any) => m.sender === "customer",
      );
      const firstAiMsg = messages.find((m: any) => m.sender === "ai_agent");

      if (firstCustomerMsg && firstAiMsg) {
        const responseTime =
          firstAiMsg.timestamp.getTime() - firstCustomerMsg.timestamp.getTime();
        totalResponseTimeMs += responseTime;
        responseCount++;
      }
    });

    const avgResponseTimeSeconds =
      responseCount > 0
        ? Math.round(totalResponseTimeMs / responseCount / 1000)
        : 0;

    // Conversion rate (conversations that led to bookings)
    const conversionRate =
      totalConversations > 0
        ? Math.round((conversationsWithBooking / totalConversations) * 100)
        : 0;

    // Unread messages
    const unreadCount = conversations.reduce(
      (sum: number, c: any) => sum + (c.unreadCount || 0),
      0,
    );

    return NextResponse.json({
      totalConversations,
      activeConversations,
      resolvedConversations,
      conversationsWithBooking,
      avgResponseTimeSeconds,
      conversionRate,
      unreadCount,
      period: `${days} days`,
    });
  } catch (error) {
    console.error("Failed to fetch conversation stats:", error);
    return NextResponse.json(
      { error: "Failed to fetch statistics" },
      { status: 500 },
    );
  }
}
