import '../../domain/entities/dashboard_summary.dart';
import '../../domain/entities/recent_operation.dart';
import '../../domain/entities/server_status.dart';
import '../../domain/repositories/dashboard_repository.dart';
import '../datasources/dashboard_datasource.dart';

class DashboardRepositoryImpl implements DashboardRepository {
  final DashboardDatasource _datasource;

  DashboardRepositoryImpl(this._datasource);

  @override
  Future<DashboardSummary> getSummary() async {
    // Fetch all data concurrently
    final results = await Future.wait([
      _datasource.fetchServers(),
      _datasource.fetchAlertEvents(),
      _datasource.fetchRecentOps(),
    ]);

    final servers = results[0];
    final alerts = results[1];
    final tasks = results[2];

    // Compute server summary
    int online = 0, warning = 0, offline = 0;
    for (final s in servers) {
      final status = (s['status'] as String? ?? '').toLowerCase();
      switch (status) {
        case 'online':
        case 'healthy':
        case 'running':
        case 'active':
          online++;
          break;
        case 'warning':
        case 'degraded':
          warning++;
          break;
        default:
          offline++;
      }
    }

    // Compute alert summary
    int critical = 0, alertWarning = 0, info = 0;
    for (final e in alerts) {
      final severity = (e['severity'] as String? ?? '').toLowerCase();
      switch (severity) {
        case 'critical':
        case 'error':
          critical++;
          break;
        case 'warning':
          alertWarning++;
          break;
        default:
          info++;
      }
    }

    // Compute task counts
    final running = tasks
        .where((t) => (t['status'] as String?)?.toLowerCase() == 'running')
        .length;

    return DashboardSummary(
      servers: ServerSummary(
        total: servers.length,
        online: online,
        warning: warning,
        offline: offline,
      ),
      alerts: AlertSummary(
        critical: critical,
        warning: alertWarning,
        info: info,
      ),
      runningTasks: running,
      totalTasks: tasks.length,
    );
  }

  @override
  Future<List<RecentOperation>> getRecentOperations({int limit = 5}) async {
    final tasks = await _datasource.fetchRecentOps(limit: limit);
    return tasks.map((task) {
      return RecentOperation(
        id: task['id']?.toString() ?? '',
        title: task['title'] as String? ?? task['name'] as String? ?? 'Untitled',
        status: task['status'] as String? ?? 'unknown',
        description: task['description'] as String?,
        priority: task['priority'] as String?,
        createdAt: _parseDateTime(
          task['created_at'] as String? ?? task['createdAt'] as String?,
        ),
      );
    }).toList();
  }

  @override
  Future<List<ServerStatus>> getServerStatuses() async {
    final servers = await _datasource.fetchServers();
    return servers.map((s) {
      return ServerStatus(
        id: s['id']?.toString() ?? '',
        hostname: s['hostname'] as String? ?? s['name'] as String? ?? '',
        status: s['status'] as String? ?? 'unknown',
        ipAddress: s['ip_address'] as String? ?? s['ipAddress'] as String?,
        cpuUsage: (s['cpu_usage'] as num?)?.toDouble() ??
            (s['cpuUsage'] as num?)?.toDouble(),
        memoryUsage: (s['memory_usage'] as num?)?.toDouble() ??
            (s['memoryUsage'] as num?)?.toDouble(),
        diskUsage: (s['disk_usage'] as num?)?.toDouble() ??
            (s['diskUsage'] as num?)?.toDouble(),
        lastChecked: _parseDateTime(
          s['last_checked'] as String? ?? s['lastChecked'] as String?,
        ),
      );
    }).toList();
  }

  DateTime? _parseDateTime(String? value) {
    if (value == null) return null;
    return DateTime.tryParse(value);
  }
}
