import { Response } from 'express';
import { AuthenticatedRequest } from '../middlewares/auth';
import { createError, asyncHandler } from '../middlewares/errorHandler';
import { QuotaService } from '../services/quotaService';
import logger from '../utils/logger';







/**
 * @route   GET /api/usage/quota/:userId
 * @desc    Get monthly quota for a user (admin/teacher only)
 * @access  Private (Admin/Teacher)
 */
export const getUserMonthlyQuota = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  const { userId } = req.params;
  
  if (req.user!.role !== 'ADMIN' && req.user!.role !== 'TEACHER') {
    throw createError('Only admins and teachers can view user quota', 403);
  }
  
  logger.info('📊 Getting user monthly quota', { 
    adminId: req.user!.id, 
    adminEmail: req.user!.email,
    userId 
  });
  
  const quotaInfo = await QuotaService.getRemainingSeconds(userId);
  
  logger.info('✅ User monthly quota retrieved', { 
    adminId: req.user!.id, 
    userId, 
    allocatedSeconds: quotaInfo.allocatedSeconds,
    usedSeconds: quotaInfo.usedSeconds,
    remainingSeconds: quotaInfo.remainingSeconds
  });
  
  res.json({
    success: true,
    data: quotaInfo
  });
});

/**
 * @route   POST /api/usage/quota/:userId
 * @desc    Set monthly quota for a user (admin/teacher only)
 * @access  Private (Admin/Teacher)
 */
export const setUserMonthlyQuota = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  const { userId } = req.params;
  const { allocatedSeconds, bonusSeconds, bonusExpiresAt } = req.body;

  if (req.user!.role !== 'ADMIN' && req.user!.role !== 'TEACHER') {
    throw createError('Only admins and teachers can set user quota', 403);
  }
  
  if (typeof allocatedSeconds !== 'number' || allocatedSeconds < 0) {
    throw createError('allocatedSeconds must be a non-negative number', 400);
  }
  
  if (bonusSeconds !== undefined && (typeof bonusSeconds !== 'number' || bonusSeconds < 0)) {
    throw createError('bonusSeconds must be a non-negative number', 400);
  }

  logger.info('📝 Setting user monthly quota', { 
    adminId: req.user!.id, 
    adminEmail: req.user!.email,
    userId, 
    allocatedSeconds, 
    bonusSeconds: bonusSeconds || 0,
    bonusExpiresAt
  });

  // Establecer cuota base
  const baseGrant = await QuotaService.setBaseQuota(
    userId, 
    allocatedSeconds, 
    `Set by ${req.user!.role.toLowerCase()} ${req.user!.name} (${req.user!.email})`
  );

  // Establecer cuota bonus si se proporciona
  let bonusGrant = null;
  if (typeof bonusSeconds === 'number') {
    const expiryDate = bonusExpiresAt ? new Date(bonusExpiresAt) : undefined;
    bonusGrant = await QuotaService.setBonusQuota(
      userId,
      bonusSeconds,
      expiryDate,
      `Bonus set by ${req.user!.role.toLowerCase()} ${req.user!.name} (${req.user!.email})`
    );
  }

  logger.info('✅ User monthly quota set successfully', { 
    adminId: req.user!.id, 
    userId, 
    allocatedSeconds, 
    bonusSeconds: bonusSeconds || 0,
    baseGrantId: baseGrant?.id,
    bonusGrantId: bonusGrant?.id
  });
  
  res.json({
    success: true,
    message: 'Monthly quota set successfully',
    data: { 
      baseGrant, 
      bonusGrant,
      allocatedSeconds,
      bonusSeconds: bonusSeconds || 0
    }
  });
});

/**
 * @route   GET /api/usage/timer/info
 * @desc    Get timer information for current user (integrates with monthly quota)
 * @access  Private (Student)
 */
export const getTimerInfo = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  const userId = req.user!.id;
  
  logger.info('⏰ Getting timer info for current user', { userId });
  
  const timerInfo = await QuotaService.getTimerInfo(userId);
  
  logger.info('✅ Timer info retrieved', { userId, timerInfo });
  
  res.json({
    success: true,
    data: timerInfo
  });
});

/**
 * @route   GET /api/usage/timer/can-use-bot
 * @desc    Check if current user can use bots based on quota
 * @access  Private (Student)
 */
export const canUserUseBot = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  const userId = req.user!.id;
  
  logger.info('🔍 Checking if current user can use bot', { userId });
  
  const result = await QuotaService.canUserUseBot(userId);
  
  logger.info('✅ Bot access check completed', { userId, result });
  
  res.json({
    success: true,
    data: result
  });
});

