import { Response } from 'express';
import { prisma } from '../index';
import { asyncHandler, createError } from '../middlewares/errorHandler';
import logger from '../utils/logger';
import { AuthenticatedRequest } from '../middlewares/auth';


/**
 * Get dashboard statistics for the current user
 */
export const getDashboardStats = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  if (!req.user) {
    throw createError('Authentication required', 401);
  }

  const userId = req.user.id;
  const userRole = req.user.role;

  let stats: any = {};

  if (userRole === 'STUDENT') {
    // Get student statistics
    const [
      totalConversations,
      assignedBots,
      recentConversations
    ] = await Promise.all([
      // Total conversations
      prisma.conversation.count({
        where: { studentId: userId }
      }),
      
      // Assigned bots
      prisma.studentBotAccess.count({
        where: { studentId: userId }
      }),
      
      // Recent conversations
      prisma.conversation.findMany({
        where: { studentId: userId },
        include: {
          bot: {
            select: {
              id: true,
              name: true,
              topic: true,
              level: true
            }
          }
        },
        orderBy: { startedAt: 'desc' },
        take: 5
      })
    ]);
    
    // Calculate total duration from all sessions
    // First get all conversation IDs for this student
    const studentConversations = await prisma.conversation.findMany({
      where: { studentId: userId },
      select: { id: true }
    });
    const conversationIds = studentConversations.map(c => c.id);
    
    // Then aggregate sessions for those conversations
    const allSessions = conversationIds.length > 0 
      ? await prisma.conversationSession.aggregate({
          where: {
            conversationId: { in: conversationIds },
            durationSeconds: { not: null }
          },
          _sum: { durationSeconds: true }
        })
      : { _sum: { durationSeconds: null } };
    const totalDurationSeconds = allSessions._sum?.durationSeconds || 0;

    stats = {
      totalConversations,
      totalDurationSeconds,
      assignedBots,
      recentConversations,
      currentLevel: 'B1' // This could be calculated based on performance
    };

  } else if (userRole === 'TEACHER') {
    // Get teacher statistics - only for assigned students
    const [
      totalStudents,
      activeStudents,
      totalBots,
      totalAssignments,
      recentAssignments
    ] = await Promise.all([
      // Total students assigned to this teacher
      prisma.user.count({
        where: { 
          role: 'STUDENT',
          assignedTeachers: { some: { teacherId: userId } }
        }
      }),
      
      // Active students (assigned students with conversations in last 30 days)
      prisma.user.count({
        where: {
          role: 'STUDENT',
          assignedTeachers: { some: { teacherId: userId } },
          conversations: {
            some: {
              startedAt: {
                gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
              }
            }
          }
        }
      }),
      
      // Total bots
      prisma.bot.count(),
      
      // Total assignments for assigned students only
      prisma.studentBotAccess.count({
        where: {
          student: {
            assignedTeachers: { some: { teacherId: userId } }
          }
        }
      }),
      
      // Recent assignments for assigned students only
      prisma.studentBotAccess.findMany({
        where: {
          student: {
            assignedTeachers: { some: { teacherId: userId } }
          }
        },
        include: {
          student: {
            select: {
              id: true,
              name: true,
              email: true
            }
          },
          bot: {
            select: {
              id: true,
              name: true,
              topic: true
            }
          }
        },
        orderBy: { grantedAt: 'desc' },
        take: 5
      })
    ]);

    stats = {
      totalStudents,
      activeStudents,
      totalBots,
      totalAssignments,
      recentAssignments
    };

  } else if (userRole === 'ADMIN') {
    // Get admin statistics
    const [
      totalUsers,
      totalBots,
      totalConversations,
      activeToday,
      recentActivity
    ] = await Promise.all([
      // Total users
      prisma.user.count(),
      
      // Total bots
      prisma.bot.count(),
      
      // Total conversations
      prisma.conversation.count(),
      
      // Active users today
      prisma.user.count({
        where: {
          conversations: {
            some: {
              startedAt: {
                gte: new Date(new Date().setHours(0, 0, 0, 0))
              }
            }
          }
        }
      }),
      
      // Recent activity (last 5 conversations)
      prisma.conversation.findMany({
        include: {
          student: {
            select: {
              id: true,
              name: true,
              email: true
            }
          },
          bot: {
            select: {
              id: true,
              name: true,
              topic: true
            }
          }
        },
        orderBy: { startedAt: 'desc' },
        take: 5
      })
    ]);

    stats = {
      totalUsers,
      totalBots,
      totalConversations,
      activeToday,
      recentActivity
    };
  }

  logger.info('Dashboard statistics retrieved successfully', {
    userId,
    userRole,
    stats
  });

  res.json({
    success: true,
    message: 'Dashboard statistics retrieved successfully',
    data: { stats }
  });
});

/**
 * Get student statistics for teachers/admins
 */
export const getStudentStats = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  if (!req.user) {
    throw createError('Authentication required', 401);
  }

  const { studentId } = req.params;

  if (req.user.role === 'STUDENT' && req.user.id !== studentId) {
    throw createError('Access denied', 403);
  }

    const [
          totalConversations,
      assignedBots,
      recentConversations
  ] = await Promise.all([
          // Total conversations
      prisma.conversation.count({
        where: { studentId }
      }),
      
      // Assigned bots
      prisma.studentBotAccess.count({
        where: { studentId }
      }),
      
      // Recent conversations
      prisma.conversation.findMany({
        where: { studentId },
      include: {
        bot: {
          select: {
            id: true,
            name: true,
            topic: true,
            level: true
          }
        }
      },
      orderBy: { startedAt: 'desc' },
      take: 10
    })
  ]);
  
  // Get conversation IDs for this student to use in aggregates
  const studentConversationIds = await prisma.conversation.findMany({
    where: { studentId },
    select: { id: true }
  });
  const conversationIds = studentConversationIds.map(c => c.id);
  
  // Average rating (if feedback system is implemented)
  const averageRatingResult = conversationIds.length > 0
    ? await prisma.feedback.aggregate({
        where: {
          conversationId: { in: conversationIds }
        },
        _avg: { rating: true }
      })
    : { _avg: { rating: null } };
  
  // Calculate total duration from all sessions
  const allSessions = conversationIds.length > 0
    ? await prisma.conversationSession.aggregate({
        where: {
          conversationId: { in: conversationIds },
          durationSeconds: { not: null }
        },
        _sum: { durationSeconds: true }
      })
    : { _sum: { durationSeconds: null } };
  const totalDurationSeconds = allSessions._sum?.durationSeconds || 0;

  const stats = {
    totalConversations,
    totalDurationSeconds,
    assignedBots,
    recentConversations,
    averageRating: averageRatingResult._avg?.rating ?? 0
  };

  logger.info('Student statistics retrieved successfully', {
    userId: req.user.id,
    studentId,
    stats
  });

  res.json({
    success: true,
    message: 'Student statistics retrieved successfully',
    data: { stats }
  });
});

/**
 * Get recent activity for the current user
 */
export const getRecentActivity = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  if (!req.user) {
    throw createError('Authentication required', 401);
  }

  const userId = req.user.id;
  const userRole = req.user.role;

  let activities: any[] = [];

  if (userRole === 'STUDENT') {
    // Get recent conversations for students
    const conversations = await prisma.conversation.findMany({
      where: { studentId: userId },
      include: {
        bot: {
          select: {
            id: true,
            name: true,
            topic: true
          }
        }
      },
      orderBy: { startedAt: 'desc' },
      take: 10
    });

    activities = conversations.map(conv => ({
      id: conv.id,
      type: 'conversation',
      title: `Conversation with ${conv.bot.name}`,
      description: `Completed conversation about ${conv.bot.topic}`,
      timestamp: conv.startedAt,
      data: conv
    }));

  } else if (userRole === 'TEACHER') {
    // Get recent bot assignments for teachers
    const assignments = await prisma.studentBotAccess.findMany({
      include: {
        student: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        bot: {
          select: {
            id: true,
            name: true,
            topic: true
          }
        }
      },
      orderBy: { grantedAt: 'desc' },
      take: 10
    });

    activities = assignments.map(assignment => ({
      id: assignment.id,
      type: 'assignment',
      title: `Assigned ${assignment.bot.name} to ${assignment.student.name}`,
      description: `Bot assignment for ${assignment.bot.topic}`,
      timestamp: assignment.grantedAt,
      data: assignment
    }));

  } else if (userRole === 'ADMIN') {
    // Get recent user registrations and bot creations for admins
    const [newUsers, newBots] = await Promise.all([
      prisma.user.findMany({
        orderBy: { createdAt: 'desc' },
        take: 5
      }),
      prisma.bot.findMany({
        orderBy: { createdAt: 'desc' },
        take: 5
      })
    ]);

    activities = [
      ...newUsers.map(user => ({
        id: user.id,
        type: 'user_registration',
        title: `New user registered: ${user.name}`,
        description: `User ${user.email} joined the platform`,
        timestamp: user.createdAt,
        data: user
      })),
      ...newBots.map(bot => ({
        id: bot.id,
        type: 'bot_creation',
        title: `New bot created: ${bot.name}`,
        description: `Bot for ${bot.topic} topic`,
        timestamp: bot.createdAt,
        data: bot
      }))
    ].sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
    .slice(0, 10);
  }

  logger.info('Recent activity retrieved successfully', {
    userId,
    userRole,
    activityCount: activities.length
  });

  res.json({
    success: true,
    message: 'Recent activity retrieved successfully',
    data: { activities }
  });
});

/**
 * Get complete dashboard data in a single request
 */
export const getCompleteDashboardData = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  if (!req.user) {
    throw createError('Authentication required', 401);
  }

  const userId = req.user.id;
  const userRole = req.user.role;

  try {
    logger.info('Getting complete dashboard data', { userId, userRole });

    // Ejecutar todas las consultas en paralelo
    const [
      activitiesResult,
      dashboardStatsResult,
      recentConversationsResult
    ] = await Promise.all([
      // Actividades recientes
      getRecentActivityData(userId, userRole).catch(err => {
        logger.error('Error getting recent activity data', { userId, userRole, error: err.message });
        return [];
      }),
      // Estadísticas del dashboard
      getDashboardStatsData(userId, userRole).catch(err => {
        logger.error('Error getting dashboard stats data', { userId, userRole, error: err.message });
        return {};
      }),
      // Conversaciones recientes (solo para estudiantes)
      userRole === 'STUDENT' 
        ? getRecentConversationsData(userId).catch(err => {
            logger.error('Error getting recent conversations data', { userId, error: err.message });
            return [];
          })
        : Promise.resolve([])
    ]);

    logger.info('Complete dashboard data retrieved successfully', {
      userId,
      userRole,
      hasActivities: activitiesResult.length > 0,
      hasStats: Object.keys(dashboardStatsResult).length > 0,
      hasConversations: recentConversationsResult.length > 0
    });

    res.json({
      success: true,
      message: 'Complete dashboard data retrieved successfully',
      data: {
        activities: activitiesResult || [],
        stats: dashboardStatsResult || {},
        recentConversations: recentConversationsResult || []
      }
    });
  } catch (error: any) {
    logger.error('Error in getCompleteDashboardData', {
      userId,
      userRole,
      error: error.message,
      stack: error.stack
    });
    throw error;
  }
});

// Funciones auxiliares para obtener datos
async function getRecentActivityData(userId: string, userRole: string) {
  try {
    let activities: any[] = [];

    if (userRole === 'STUDENT') {
    // Get recent conversations for students
    const conversations = await prisma.conversation.findMany({
      where: { studentId: userId },
      include: {
        bot: {
          select: {
            id: true,
            name: true,
            topic: true
          }
        }
      },
      orderBy: { startedAt: 'desc' },
      take: 10
    });

    activities = conversations.map(conv => ({
      id: conv.id,
      type: 'conversation',
      title: `Conversation with ${conv.bot.name}`,
      description: `Completed conversation about ${conv.bot.topic}`,
      timestamp: conv.startedAt,
      data: conv
    }));

  } else if (userRole === 'TEACHER') {
    // Get recent bot assignments for teachers
    const assignments = await prisma.studentBotAccess.findMany({
      include: {
        student: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        bot: {
          select: {
            id: true,
            name: true,
            topic: true
          }
        }
      },
      orderBy: { grantedAt: 'desc' },
      take: 10
    });

    activities = assignments.map(assignment => ({
      id: assignment.id,
      type: 'assignment',
      title: `Assigned ${assignment.bot.name} to ${assignment.student.name}`,
      description: `Bot assignment for ${assignment.bot.topic}`,
      timestamp: assignment.grantedAt,
      data: assignment
    }));

  } else if (userRole === 'ADMIN') {
    // Get recent user registrations and bot creations for admins
    const [newUsers, newBots] = await Promise.all([
      prisma.user.findMany({
        orderBy: { createdAt: 'desc' },
        take: 5
      }),
      prisma.bot.findMany({
        orderBy: { createdAt: 'desc' },
        take: 5
      })
    ]);

    activities = [
      ...newUsers.map(user => ({
        id: user.id,
        type: 'user_registration',
        title: `New user registered: ${user.name}`,
        description: `User ${user.email} joined the platform`,
        timestamp: user.createdAt,
        data: user
      })),
      ...newBots.map(bot => ({
        id: bot.id,
        type: 'bot_creation',
        title: `New bot created: ${bot.name}`,
        description: `Bot for ${bot.topic} topic`,
        timestamp: bot.createdAt,
        data: bot
      }))
    ].sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
    .slice(0, 10);
    }

    return activities;
  } catch (error: any) {
    logger.error('❌ Error in getRecentActivityData', {
      userId,
      userRole,
      error: error.message,
      stack: error.stack
    });
    throw error;
  }
}

async function getDashboardStatsData(userId: string, userRole: string) {
  try {
    let stats: any = {};

    if (userRole === 'STUDENT') {
    // Get student statistics
    const [
      totalConversations,
      assignedBots,
      recentConversations
    ] = await Promise.all([
      // Total conversations
      prisma.conversation.count({
        where: { studentId: userId }
      }),
      
      // Assigned bots
      prisma.studentBotAccess.count({
        where: { studentId: userId }
      }),
      
      // Recent conversations
      prisma.conversation.findMany({
        where: { studentId: userId },
        include: {
          bot: {
            select: {
              id: true,
              name: true,
              topic: true,
              level: true
            }
          }
        },
        orderBy: { startedAt: 'desc' },
        take: 5
      })
    ]);
    
    // Calculate total duration from all sessions
    // First get all conversation IDs for this student
    const studentConversations = await prisma.conversation.findMany({
      where: { studentId: userId },
      select: { id: true }
    });
    const conversationIds = studentConversations.map(c => c.id);
    
    // Then aggregate sessions for those conversations
    const allSessions = conversationIds.length > 0 
      ? await prisma.conversationSession.aggregate({
          where: {
            conversationId: { in: conversationIds },
            durationSeconds: { not: null }
          },
          _sum: { durationSeconds: true }
        })
      : { _sum: { durationSeconds: null } };
    const totalDurationSeconds = allSessions._sum?.durationSeconds || 0;

    stats = {
      totalConversations,
      totalDurationSeconds,
      assignedBots,
      recentConversations,
      currentLevel: 'B1' // This could be calculated based on performance
    };

  } else if (userRole === 'TEACHER') {
    // Get teacher statistics - only for assigned students
    const [
      totalStudents,
      activeStudents,
      totalBots,
      totalAssignments,
      recentAssignments
    ] = await Promise.all([
      // Total students assigned to this teacher
      prisma.user.count({
        where: { 
          role: 'STUDENT',
          assignedTeachers: { some: { teacherId: userId } }
        }
      }),
      
      // Active students (assigned students with conversations in last 30 days)
      prisma.user.count({
        where: {
          role: 'STUDENT',
          assignedTeachers: { some: { teacherId: userId } },
          conversations: {
            some: {
              startedAt: {
                gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
              }
            }
          }
        }
      }),
      
      // Total bots
      prisma.bot.count(),
      
      // Total assignments for assigned students only
      prisma.studentBotAccess.count({
        where: {
          student: {
            assignedTeachers: { some: { teacherId: userId } }
          }
        }
      }),
      
      // Recent assignments for assigned students only
      prisma.studentBotAccess.findMany({
        where: {
          student: {
            assignedTeachers: { some: { teacherId: userId } }
          }
        },
        include: {
          student: {
            select: {
              id: true,
              name: true,
              email: true
            }
          },
          bot: {
            select: {
              id: true,
              name: true,
              topic: true
            }
          }
        },
        orderBy: { grantedAt: 'desc' },
        take: 5
      })
    ]);

    stats = {
      totalStudents,
      activeStudents,
      totalBots,
      totalAssignments,
      recentAssignments
    };

  } else if (userRole === 'ADMIN') {
    // Get admin statistics
    const [
      totalUsers,
      totalBots,
      totalConversations,
      activeToday,
      recentActivity
    ] = await Promise.all([
      // Total users
      prisma.user.count(),
      
      // Total bots
      prisma.bot.count(),
      
      // Total conversations
      prisma.conversation.count(),
      
      // Active users today
      prisma.user.count({
        where: {
          conversations: {
            some: {
              startedAt: {
                gte: new Date(new Date().setHours(0, 0, 0, 0))
              }
            }
          }
        }
      }),
      
      // Recent activity (last 5 conversations)
      prisma.conversation.findMany({
        include: {
          student: {
            select: {
              id: true,
              name: true,
              email: true
            }
          },
          bot: {
            select: {
              id: true,
              name: true,
              topic: true
            }
          }
        },
        orderBy: { startedAt: 'desc' },
        take: 5
      })
    ]);

    stats = {
      totalUsers,
      totalBots,
      totalConversations,
      activeToday,
      recentActivity
    };
    }

    return stats;
  } catch (error: any) {
    logger.error('❌ Error in getDashboardStatsData', {
      userId,
      userRole,
      error: error.message,
      stack: error.stack
    });
    throw error;
  }
}

async function getRecentConversationsData(userId: string) {
  try {
    const conversations = await prisma.conversation.findMany({
      where: { studentId: userId },
      include: {
        bot: {
          select: {
            id: true,
            name: true,
            level: true,
            topic: true,
            imageUrl: true
          }
        }
      },
      orderBy: { startedAt: 'desc' },
      take: 10
    });

  // Calculate durations from sessions and get last session date
  let durationMap = new Map<string, number>();
  let lastSessionMap = new Map<string, Date | null>();
  
  if (conversations.length > 0) {
    const conversationIds = conversations.map(c => c.id);
    
    // Get all sessions for these conversations
    const allSessions = await prisma.conversationSession.findMany({
      where: { 
        conversationId: { in: conversationIds }
      },
      select: { 
        conversationId: true,
        durationSeconds: true,
        endedAt: true,
        updatedAt: true
      }
    });
    
    // Process sessions: calculate durations and find last session date for each conversation
    // Group by conversationId and process
    const sessionsByConv = new Map<string, typeof allSessions>();
    allSessions.forEach(session => {
      const convId = session.conversationId;
      if (!sessionsByConv.has(convId)) {
        sessionsByConv.set(convId, []);
      }
      sessionsByConv.get(convId)!.push(session);
    });
    
    // For each conversation, calculate totals and find most recent session
    sessionsByConv.forEach((sessions, convId) => {
      // Calculate total duration
      let totalDuration = 0;
      sessions.forEach(session => {
        if (session.durationSeconds !== null && session.durationSeconds !== undefined) {
          totalDuration += session.durationSeconds;
        }
      });
      if (totalDuration > 0) {
        durationMap.set(convId, totalDuration);
      }
      
      // Find most recent session (prioritize endedAt, fallback to updatedAt)
      const sortedSessions = sessions.sort((a, b) => {
        const aDate = a.endedAt || a.updatedAt;
        const bDate = b.endedAt || b.updatedAt;
        return bDate.getTime() - aDate.getTime();
      });
      
      if (sortedSessions.length > 0) {
        const mostRecent = sortedSessions[0];
        lastSessionMap.set(convId, mostRecent.endedAt || mostRecent.updatedAt);
      }
    });
  }

  const mapped = conversations.map(conv => {
    const lastSessionDate = lastSessionMap.get(conv.id);
    return {
      id: conv.id,
      bot: {
        id: conv.bot.id,
        name: conv.bot.name,
        level: conv.bot.level,
        imageUrl: conv.bot.imageUrl
      },
      summary: conv.summary,
      transcript: conv.transcript,
      startedAt: conv.startedAt.toISOString(),
      updatedAt: conv.updatedAt.toISOString(),
      lastSessionDate: lastSessionDate ? lastSessionDate.toISOString() : conv.updatedAt.toISOString(),
      durationSeconds: durationMap.get(conv.id) || conv.durationSeconds || 0,
      openaiSummary: conv.openaiSummary,
      openaiEvaluation: conv.openaiEvaluation,
      openaiFeedback: conv.openaiFeedback,
      openaiTranscript: conv.openaiTranscript,
      feedbackStatus: conv.feedbackStatus
    };
  });
  
    logger.info('📋 getRecentConversationsData mapped conversations', {
      count: mapped.length,
      botsWithImages: mapped.filter(c => c.bot?.imageUrl).length,
      sampleBot: mapped[0]?.bot
    });
    
    return mapped;
  } catch (error: any) {
    logger.error('❌ Error in getRecentConversationsData', {
      userId,
      error: error.message,
      stack: error.stack
    });
    throw error;
  }
}

/**
 * Get complete teacher dashboard data in a single request
 */
export const getCompleteTeacherDashboardData = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  if (!req.user) {
    throw createError('Authentication required', 401);
  }

  const userRole = req.user.role;
  
  if (userRole !== 'TEACHER' && userRole !== 'ADMIN') {
    throw createError('Access denied', 403);
  }

  // Build student filter - teachers can only see their assigned students
  const studentWhere: any = { role: 'STUDENT' };
  if (userRole === 'TEACHER') {
    studentWhere.assignedTeachers = { some: { teacherId: req.user.id } };
  }

  // Ejecutar todas las consultas en paralelo
  const [
    studentsResult,
    botsResult,
    assignmentsResult,
    statsResult
  ] = await Promise.all([
    // Obtener estudiantes (filtrados por profesor si es teacher)
    prisma.user.findMany({
      where: studentWhere,
      select: {
        id: true,
        name: true,
        email: true,
        createdAt: true,
        updatedAt: true
      }
    }),
    // Obtener bots
    prisma.bot.findMany({
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    }),
    // Obtener asignaciones (solo de estudiantes asignados si es teacher)
    prisma.studentBotAccess.findMany({
      where: userRole === 'TEACHER' ? {
        student: {
          assignedTeachers: { some: { teacherId: req.user.id } }
        }
      } : undefined,
      include: {
        student: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        bot: {
          select: {
            id: true,
            name: true,
            level: true
          }
        }
      }
    }),
    // Obtener estadísticas de estudiantes (batch) - filtrado por profesor si es teacher
    getStudentsStatsBatch(userRole === 'TEACHER' ? req.user.id : undefined)
  ]);

  logger.info('Complete teacher dashboard data retrieved successfully', {
    userId: req.user.id,
    userRole,
    studentsCount: studentsResult.length,
    botsCount: botsResult.length,
    assignmentsCount: assignmentsResult.length,
    statsCount: statsResult.length
  });

  res.json({
    success: true,
    message: 'Complete teacher dashboard data retrieved successfully',
    data: {
      students: studentsResult,
      bots: botsResult,
      assignments: assignmentsResult,
      studentStats: statsResult
    }
  });
});

async function getStudentsStatsBatch(teacherId?: string) {
  // Obtener estudiantes (filtrados por profesor si se proporciona teacherId)
  const studentWhere: any = { role: 'STUDENT' };
  if (teacherId) {
    studentWhere.assignedTeachers = { some: { teacherId } };
  }
  
  const students = await prisma.user.findMany({
    where: studentWhere,
    select: { id: true }
  });

  const studentIds = students.map(s => s.id);
  
  // Obtener estadísticas en batch
  const results = [];
  for (const studentId of studentIds) {
    const [totalConversations, assignedBots, recentConversations] = await Promise.all([
      prisma.conversation.count({ where: { studentId } }),
      prisma.studentBotAccess.count({ where: { studentId } }),
      prisma.conversation.findMany({ 
        where: { studentId }, 
        select: { id: true, startedAt: true }, 
        orderBy: { startedAt: 'desc' }, 
        take: 1 
      })
    ]);
    
    const allConversations = await prisma.conversation.aggregate({
      where: {
        studentId,
        durationSeconds: { not: null }
      },
      _sum: { durationSeconds: true }
    });
    
    results.push({
      studentId,
      totalConversations,
      totalDurationSeconds: allConversations._sum?.durationSeconds || 0,
      assignedBots,
      lastActivityAt: recentConversations[0]?.startedAt || null
    });
  }
  
  return results;
} 