/**
 * Analytics MCP Server
 *
 * Efficient data operations for workflow analytics.
 * Returns aggregated data to minimize token usage.
 */

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

/**
 * Get workflow analytics summary for a date range
 */
export async function getWorkflowAnalyticsSummary(userId: string, days = 7) {
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - days);
  startDate.setHours(0, 0, 0, 0);

  const analytics = await prisma.workflowAnalytics.findMany({
    where: {
      userId,
      date: { gte: startDate },
    },
    select: {
      workflowType: true,
      date: true,
      messagesReceived: true,
      messagesSent: true,
      appointmentsBooked: true,
      quotationsSent: true,
      leadsGenerated: true,
    },
    orderBy: { date: "desc" },
  });

  // Aggregate by workflow type
  const byWorkflowType = analytics.reduce(
    (acc, record) => {
      if (!acc[record.workflowType]) {
        acc[record.workflowType] = {
          workflowType: record.workflowType,
          messagesReceived: 0,
          messagesSent: 0,
          appointmentsBooked: 0,
          quotationsSent: 0,
          leadsGenerated: 0,
        };
      }

      acc[record.workflowType].messagesReceived += record.messagesReceived;
      acc[record.workflowType].messagesSent += record.messagesSent;
      acc[record.workflowType].appointmentsBooked += record.appointmentsBooked;
      acc[record.workflowType].quotationsSent += record.quotationsSent;
      acc[record.workflowType].leadsGenerated += record.leadsGenerated;

      return acc;
    },
    {} as Record<string, any>,
  );

  // Calculate totals
  const totals = {
    messagesReceived: 0,
    messagesSent: 0,
    appointmentsBooked: 0,
    quotationsSent: 0,
    leadsGenerated: 0,
  };

  Object.values(byWorkflowType).forEach((workflow: any) => {
    totals.messagesReceived += workflow.messagesReceived;
    totals.messagesSent += workflow.messagesSent;
    totals.appointmentsBooked += workflow.appointmentsBooked;
    totals.quotationsSent += workflow.quotationsSent;
    totals.leadsGenerated += workflow.leadsGenerated;
  });

  return {
    days,
    startDate: startDate.toISOString(),
    totals,
    byWorkflowType: Object.values(byWorkflowType),
  };
}

/**
 * Get daily analytics for a specific date
 */
export async function getDailyAnalytics(userId: string, date: Date) {
  const dateOnly = new Date(date);
  dateOnly.setHours(0, 0, 0, 0);

  const analytics = await prisma.workflowAnalytics.findMany({
    where: {
      userId,
      date: dateOnly,
    },
    select: {
      workflowType: true,
      messagesReceived: true,
      messagesSent: true,
      appointmentsBooked: true,
      quotationsSent: true,
      leadsGenerated: true,
    },
  });

  return analytics;
}

/**
 * Get analytics trend for a workflow type
 */
export async function getWorkflowTrend(
  userId: string,
  workflowType: string,
  days = 7,
) {
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - days);
  startDate.setHours(0, 0, 0, 0);

  const analytics = await prisma.workflowAnalytics.findMany({
    where: {
      userId,
      workflowType,
      date: { gte: startDate },
    },
    select: {
      date: true,
      messagesReceived: true,
      messagesSent: true,
      appointmentsBooked: true,
    },
    orderBy: { date: "asc" },
  });

  return analytics;
}

/**
 * Get top performing workflows by messages handled
 */
export async function getTopWorkflows(userId: string, days = 30, limit = 5) {
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - days);

  const analytics = await prisma.workflowAnalytics.findMany({
    where: {
      userId,
      date: { gte: startDate },
    },
    select: {
      workflowType: true,
      messagesReceived: true,
      messagesSent: true,
      appointmentsBooked: true,
      leadsGenerated: true,
    },
  });

  // Aggregate by workflow
  const workflowTotals = analytics.reduce(
    (acc, record) => {
      if (!acc[record.workflowType]) {
        acc[record.workflowType] = {
          workflowType: record.workflowType,
          totalMessages: 0,
          messagesReceived: 0,
          messagesSent: 0,
          appointmentsBooked: 0,
          leadsGenerated: 0,
        };
      }

      acc[record.workflowType].messagesReceived += record.messagesReceived;
      acc[record.workflowType].messagesSent += record.messagesSent;
      acc[record.workflowType].totalMessages +=
        record.messagesReceived + record.messagesSent;
      acc[record.workflowType].appointmentsBooked += record.appointmentsBooked;
      acc[record.workflowType].leadsGenerated += record.leadsGenerated;

      return acc;
    },
    {} as Record<string, any>,
  );

  // Sort by total messages and take top N
  return Object.values(workflowTotals)
    .sort((a: any, b: any) => b.totalMessages - a.totalMessages)
    .slice(0, limit);
}

/**
 * Get analytics comparison between two periods
 */
export async function getPeriodComparison(userId: string, days = 7) {
  const currentStart = new Date();
  currentStart.setDate(currentStart.getDate() - days);

  const previousStart = new Date();
  previousStart.setDate(previousStart.getDate() - days * 2);

  const previousEnd = new Date(currentStart);

  // Get current period
  const currentAnalytics = await prisma.workflowAnalytics.findMany({
    where: {
      userId,
      date: { gte: currentStart },
    },
    select: {
      messagesReceived: true,
      messagesSent: true,
      appointmentsBooked: true,
      leadsGenerated: true,
    },
  });

  // Get previous period
  const previousAnalytics = await prisma.workflowAnalytics.findMany({
    where: {
      userId,
      date: {
        gte: previousStart,
        lt: previousEnd,
      },
    },
    select: {
      messagesReceived: true,
      messagesSent: true,
      appointmentsBooked: true,
      leadsGenerated: true,
    },
  });

  // Calculate totals
  const calculateTotals = (records: any[]) => ({
    messagesReceived: records.reduce((sum, r) => sum + r.messagesReceived, 0),
    messagesSent: records.reduce((sum, r) => sum + r.messagesSent, 0),
    appointmentsBooked: records.reduce(
      (sum, r) => sum + r.appointmentsBooked,
      0,
    ),
    leadsGenerated: records.reduce((sum, r) => sum + r.leadsGenerated, 0),
  });

  const currentTotals = calculateTotals(currentAnalytics);
  const previousTotals = calculateTotals(previousAnalytics);

  // Calculate percentage changes
  const calculateChange = (current: number, previous: number) => {
    if (previous === 0) return current > 0 ? 100 : 0;
    return ((current - previous) / previous) * 100;
  };

  return {
    current: currentTotals,
    previous: previousTotals,
    changes: {
      messagesReceived: calculateChange(
        currentTotals.messagesReceived,
        previousTotals.messagesReceived,
      ),
      messagesSent: calculateChange(
        currentTotals.messagesSent,
        previousTotals.messagesSent,
      ),
      appointmentsBooked: calculateChange(
        currentTotals.appointmentsBooked,
        previousTotals.appointmentsBooked,
      ),
      leadsGenerated: calculateChange(
        currentTotals.leadsGenerated,
        previousTotals.leadsGenerated,
      ),
    },
    days,
  };
}
