import AuditLogModel from '../../models/AuditLog';
import mongoose from 'mongoose';

export class AuditLogClass {
  // Create a new audit log entry
  static async createLog(logData: {
    action: string;
    resource_type: string;
    user_id?: mongoose.Types.ObjectId;
    description: string;
    severity?: string;
    status?: string;
    metadata?: any;
    compliance_flags?: any;
    tags?: string[];
  }) {
    try {
      const auditLog = new AuditLogModel(logData);
      return await auditLog.save();
    } catch (error) {
      throw new Error(`Failed to create audit log: ${error}`);
    }
  }

  // Get audit logs with filtering and pagination
  static async getLogs(
    filters: {
      user_id?: mongoose.Types.ObjectId;
      action?: string;
      resource_type?: string;
      severity?: string;
      status?: string;
      startDate?: Date;
      endDate?: Date;
      page?: number;
      limit?: number;
    } = {}
  ) {
    try {
      const {
        user_id,
        action,
        resource_type,
        severity,
        status,
        startDate,
        endDate,
        page = 1,
        limit = 50,
      } = filters;

      const query: any = {};

      if (user_id) query.user_id = user_id;
      if (action) query.action = action;
      if (resource_type) query.resource_type = resource_type;
      if (severity) query.severity = severity;
      if (status) query.status = status;

      if (startDate || endDate) {
        query.timestamp = {};
        if (startDate) query.timestamp.$gte = startDate;
        if (endDate) query.timestamp.$lte = endDate;
      }

      const skip = (page - 1) * limit;

      const [logs, total] = await Promise.all([
        AuditLogModel.find(query)
          .sort({ timestamp: -1 })
          .skip(skip)
          .limit(limit)
          .populate('user_id', 'name email')
          .lean(),
        AuditLogModel.countDocuments(query),
      ]);

      return {
        logs,
        pagination: {
          current_page: page,
          total_pages: Math.ceil(total / limit),
          total_records: total,
          per_page: limit,
        },
      };
    } catch (error) {
      throw new Error(`Failed to retrieve audit logs: ${error}`);
    }
  }
}
