const ActivityLogger = require('../utils/activityLogger');
const Account = require('../models/account.model');
const mongoose = require('mongoose');

class ActivityLogController {
  static async getActivityLogs(req, res) {
    try {
      const page = parseInt(req.query.page) || 1;
      const limit = parseInt(req.query.limit) || 50;
      const filters = {};

      // Apply filters
      if (req.query.adminId) {
        if (!mongoose.Types.ObjectId.isValid(req.query.adminId)) {
          return res.status(400).json({
            success: false,
            message: 'Invalid admin ID format',
          });
        }
        filters.adminId = req.query.adminId;
      }
      
      if (req.query.action) filters.action = req.query.action;
      if (req.query.targetType) filters.targetType = req.query.targetType;
      
      if (req.query.startDate) {
        const startDate = new Date(req.query.startDate);
        if (isNaN(startDate)) {
          return res.status(400).json({
            success: false,
            message: 'Invalid start date format',
          });
        }
        filters.startDate = startDate;
      }
      
      if (req.query.endDate) {
        const endDate = new Date(req.query.endDate);
        if (isNaN(endDate)) {
          return res.status(400).json({
            success: false,
            message: 'Invalid end date format',
          });
        }
        filters.endDate = endDate;
      }

      const result = await ActivityLogger.getActivityLogs(page, limit, filters);

      // Format the response to match expected structure
      const formattedLogs = result.logs.map(log => ({
        id: log._id,
        adminId: log.adminId,
        admin: log.admin ? {
          id: log.admin._id,
          firstName: log.admin.firstName,
          lastName: log.admin.lastName,
          email: log.admin.email,
        } : null,
        action: log.action,
        description: log.description,
        targetType: log.targetType,
        targetId: log.targetId,
        metadata: log.metadata,
        ipAddress: log.ipAddress,
        userAgent: log.userAgent,
        createdAt: log.createdAt,
      }));

      return res.status(200).json({
        success: true,
        data: {
          logs: formattedLogs,
          pagination: {
            totalItems: result.pagination.totalItems,
            totalPages: result.pagination.totalPages,
            currentPage: page,
            itemsPerPage: limit,
            hasNextPage: page < result.pagination.totalPages,
            hasPreviousPage: page > 1,
          },
        },
      });
    } catch (error) {
      console.error('Error fetching activity logs:', error);
      return res.status(500).json({
        success: false,
        message: 'Internal server error',
        error: error.message,
      });
    }
  }

  static async getAdminActions(req, res) {
    try {
      const { adminId } = req.params;
      const page = parseInt(req.query.page) || 1;
      const limit = parseInt(req.query.limit) || 20;

      if (!mongoose.Types.ObjectId.isValid(adminId)) {
        return res.status(400).json({
          success: false,
          message: 'Invalid admin ID format',
        });
      }

      // First check if admin exists
      const admin = await Account.findById(adminId).select('firstName lastName email');
      if (!admin) {
        return res.status(404).json({
          success: false,
          message: 'Admin not found',
        });
      }

      const result = await ActivityLogger.getActivityLogs(page, limit, {
        adminId,
      });

      // Format the response
      const formattedLogs = result.logs.map(log => ({
        id: log._id,
        action: log.action,
        description: log.description,
        targetType: log.targetType,
        targetId: log.targetId,
        metadata: log.metadata,
        ipAddress: log.ipAddress,
        userAgent: log.userAgent,
        createdAt: log.createdAt,
      }));

      return res.status(200).json({
        success: true,
        data: {
          admin: {
            id: admin._id,
            firstName: admin.firstName,
            lastName: admin.lastName,
            email: admin.email,
          },
          logs: formattedLogs,
          pagination: {
            totalItems: result.pagination.totalItems,
            totalPages: result.pagination.totalPages,
            currentPage: page,
            itemsPerPage: limit,
            hasNextPage: page < result.pagination.totalPages,
            hasPreviousPage: page > 1,
          },
        },
      });
    } catch (error) {
      console.error('Error fetching admin actions:', error);
      return res.status(500).json({
        success: false,
        message: 'Internal server error',
        error: error.message,
      });
    }
  }

  /**
   * Get activity logs for a specific target (e.g., user, product, order)
   */
  static async getTargetActivity(req, res) {
    try {
      const { targetType, targetId } = req.params;
      const page = parseInt(req.query.page) || 1;
      const limit = parseInt(req.query.limit) || 20;

      if (!mongoose.Types.ObjectId.isValid(targetId)) {
        return res.status(400).json({
          success: false,
          message: 'Invalid target ID format',
        });
      }

      const result = await ActivityLogger.getActivityLogs(page, limit, {
        targetType,
        targetId,
      });

      const formattedLogs = result.logs.map(log => ({
        id: log._id,
        adminId: log.adminId,
        admin: log.admin ? {
          id: log.admin._id,
          firstName: log.admin.firstName,
          lastName: log.admin.lastName,
          email: log.admin.email,
        } : null,
        action: log.action,
        description: log.description,
        metadata: log.metadata,
        createdAt: log.createdAt,
      }));

      return res.status(200).json({
        success: true,
        data: {
          targetType,
          targetId,
          logs: formattedLogs,
          pagination: {
            totalItems: result.pagination.totalItems,
            totalPages: result.pagination.totalPages,
            currentPage: page,
            itemsPerPage: limit,
            hasNextPage: page < result.pagination.totalPages,
            hasPreviousPage: page > 1,
          },
        },
      });
    } catch (error) {
      console.error('Error fetching target activity:', error);
      return res.status(500).json({
        success: false,
        message: 'Internal server error',
        error: error.message,
      });
    }
  }

  /**
   * Get activity summary statistics
   */
  static async getActivitySummary(req, res) {
    try {
      const { days = 30 } = req.query;
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - parseInt(days));

      // This would need to be implemented in ActivityLogger
      const summary = await ActivityLogger.getActivitySummary(startDate);

      return res.status(200).json({
        success: true,
        data: summary,
      });
    } catch (error) {
      console.error('Error fetching activity summary:', error);
      return res.status(500).json({
        success: false,
        message: 'Internal server error',
        error: error.message,
      });
    }
  }

  /**
   * Export activity logs (for admin reports)
   */
  static async exportActivityLogs(req, res) {
    try {
      const { startDate, endDate, format = 'json' } = req.query;
      
      const filters = {};
      
      if (startDate) {
        filters.startDate = new Date(startDate);
      }
      
      if (endDate) {
        filters.endDate = new Date(endDate);
      }

      // Get all logs without pagination for export
      const logs = await ActivityLogger.exportLogs(filters);

      if (format === 'csv') {
        // Convert to CSV format
        const csv = this.convertToCSV(logs);
        
        res.setHeader('Content-Type', 'text/csv');
        res.setHeader('Content-Disposition', 'attachment; filename=activity-logs.csv');
        return res.status(200).send(csv);
      }

      // Default JSON format
      return res.status(200).json({
        success: true,
        data: logs,
      });
    } catch (error) {
      console.error('Error exporting activity logs:', error);
      return res.status(500).json({
        success: false,
        message: 'Internal server error',
        error: error.message,
      });
    }
  }

  /**
   * Helper method to convert logs to CSV
   */
  static convertToCSV(logs) {
    const headers = ['ID', 'Admin', 'Action', 'Description', 'Target Type', 'Target ID', 'IP Address', 'User Agent', 'Created At'];
    
    const rows = logs.map(log => [
      log._id,
      log.admin ? `${log.admin.firstName} ${log.admin.lastName}` : 'Unknown',
      log.action,
      log.description,
      log.targetType,
      log.targetId,
      log.ipAddress,
      log.userAgent,
      new Date(log.createdAt).toISOString(),
    ]);

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
    ].join('\n');

    return csvContent;
  }
}

module.exports = ActivityLogController;