/**
 * Conversations MCP Server
 *
 * Efficient data operations for conversation management.
 * Returns summary data without full message content to optimize token usage.
 */

import { prisma } from "@/lib/db";

/**
 * Get conversation summary list without full message content
 */
export async function getConversationSummary(userId: string, limit = 10) {
  const conversations = await prisma.conversationLog.findMany({
    where: { userId },
    select: {
      id: true,
      platform: true,
      customerPhone: true,
      customerName: true,
      status: true,
      createdAt: true,
      updatedAt: true,
      // Don't load full messages array - just count
      messages: true,
    },
    orderBy: { updatedAt: "desc" },
    take: limit,
  });

  // Transform to include message count instead of full messages
  return conversations.map((conv) => ({
    id: conv.id,
    platform: conv.platform,
    customerPhone: conv.customerPhone,
    customerName: conv.customerName,
    status: conv.status,
    createdAt: conv.createdAt,
    updatedAt: conv.updatedAt,
    messageCount: Array.isArray(conv.messages) ? conv.messages.length : 0,
  }));
}

/**
 * Get daily conversation statistics
 */
export async function getDailyConversationStats(userId: string, date: Date) {
  const startOfDay = new Date(date);
  startOfDay.setHours(0, 0, 0, 0);

  const endOfDay = new Date(date);
  endOfDay.setHours(23, 59, 59, 999);

  const conversations = await prisma.conversationLog.findMany({
    where: {
      userId,
      createdAt: {
        gte: startOfDay,
        lte: endOfDay,
      },
    },
    select: {
      platform: true,
      messages: true,
      status: true,
    },
  });

  // Calculate stats
  const stats = {
    total: conversations.length,
    byPlatform: conversations.reduce(
      (acc, c) => {
        acc[c.platform] = (acc[c.platform] || 0) + 1;
        return acc;
      },
      {} as Record<string, number>,
    ),
    byStatus: conversations.reduce(
      (acc, c) => {
        acc[c.status] = (acc[c.status] || 0) + 1;
        return acc;
      },
      {} as Record<string, number>,
    ),
    messages: {
      received: 0,
      sent: 0,
      total: 0,
    },
  };

  // Count messages
  conversations.forEach((conv) => {
    if (Array.isArray(conv.messages)) {
      const messages = conv.messages as any[];
      stats.messages.total += messages.length;

      messages.forEach((msg: any) => {
        if (msg.role === "customer" || msg.role === "user") {
          stats.messages.received++;
        } else {
          stats.messages.sent++;
        }
      });
    }
  });

  return stats;
}

/**
 * Get weekly conversation trend (last 7 days)
 */
export async function getWeeklyTrend(userId: string) {
  const today = new Date();
  const sevenDaysAgo = new Date(today);
  sevenDaysAgo.setDate(today.getDate() - 7);

  const conversations = await prisma.conversationLog.findMany({
    where: {
      userId,
      createdAt: {
        gte: sevenDaysAgo,
      },
    },
    select: {
      createdAt: true,
      platform: true,
      status: true,
    },
    orderBy: { createdAt: "asc" },
  });

  // Group by day
  const dailyStats = new Map<string, number>();

  conversations.forEach((conv) => {
    const dateKey = conv.createdAt.toISOString().split("T")[0];
    dailyStats.set(dateKey, (dailyStats.get(dateKey) || 0) + 1);
  });

  // Create array of last 7 days with counts
  const trend = [];
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(today.getDate() - i);
    const dateKey = date.toISOString().split("T")[0];

    trend.push({
      date: dateKey,
      count: dailyStats.get(dateKey) || 0,
    });
  }

  return trend;
}

/**
 * Get conversation platform distribution
 */
export async function getPlatformDistribution(userId: string) {
  const conversations = await prisma.conversationLog.findMany({
    where: { userId },
    select: { platform: true },
  });

  const distribution = conversations.reduce(
    (acc, c) => {
      acc[c.platform] = (acc[c.platform] || 0) + 1;
      return acc;
    },
    {} as Record<string, number>,
  );

  return distribution;
}

/**
 * Get recent conversations count by status
 */
export async function getStatusSummary(userId: string, days = 30) {
  const since = new Date();
  since.setDate(since.getDate() - days);

  const conversations = await prisma.conversationLog.findMany({
    where: {
      userId,
      createdAt: { gte: since },
    },
    select: { status: true },
  });

  const summary = conversations.reduce(
    (acc, c) => {
      acc[c.status] = (acc[c.status] || 0) + 1;
      return acc;
    },
    {} as Record<string, number>,
  );

  return {
    total: conversations.length,
    byStatus: summary,
    days,
  };
}
