class OfflineLocationRecord {
  const OfflineLocationRecord({
    this.id,
    required this.clientId,
    required this.deviceUuid,
    required this.latitude,
    required this.longitude,
    required this.accuracy,
    required this.recordedAt,
    this.altitude,
    this.speed,
    this.bearing,
    this.batteryPercentage,
    this.provider,
    this.attempts = 0,
    this.nextAttemptAt,
  });

  final int? id;
  final String clientId;
  final String deviceUuid;
  final double latitude;
  final double longitude;
  final double accuracy;
  final DateTime recordedAt;
  final double? altitude;
  final double? speed;
  final double? bearing;
  final int? batteryPercentage;
  final String? provider;
  final int attempts;
  final DateTime? nextAttemptAt;

  Map<String, Object?> toDatabase() => <String, Object?>{
        'client_id': clientId,
        'device_uuid': deviceUuid,
        'latitude': latitude,
        'longitude': longitude,
        'accuracy': accuracy,
        'altitude': altitude,
        'speed': speed,
        'bearing': bearing,
        'battery_percentage': batteryPercentage,
        'provider': provider,
        'recorded_at': recordedAt.toUtc().toIso8601String(),
        'attempts': attempts,
        'next_attempt_at': nextAttemptAt?.toUtc().toIso8601String(),
        'created_at': DateTime.now().toUtc().toIso8601String(),
      };

  Map<String, Object?> toApi() => <String, Object?>{
        'client_id': clientId,
        'device_uuid': deviceUuid,
        'latitude': latitude,
        'longitude': longitude,
        'accuracy': accuracy,
        'altitude': altitude,
        'speed': speed,
        'bearing': bearing,
        'battery_percentage': batteryPercentage,
        'provider': provider,
        'recorded_at': recordedAt.toUtc().toIso8601String(),
      };

  factory OfflineLocationRecord.fromDatabase(Map<String, Object?> row) {
    DateTime? optionalDate(Object? value) => value is String && value.isNotEmpty
        ? DateTime.parse(value).toUtc()
        : null;

    return OfflineLocationRecord(
      id: row['id'] as int?,
      clientId: row['client_id']! as String,
      deviceUuid: row['device_uuid']! as String,
      latitude: (row['latitude']! as num).toDouble(),
      longitude: (row['longitude']! as num).toDouble(),
      accuracy: (row['accuracy']! as num).toDouble(),
      altitude: (row['altitude'] as num?)?.toDouble(),
      speed: (row['speed'] as num?)?.toDouble(),
      bearing: (row['bearing'] as num?)?.toDouble(),
      batteryPercentage: row['battery_percentage'] as int?,
      provider: row['provider'] as String?,
      recordedAt: DateTime.parse(row['recorded_at']! as String).toUtc(),
      attempts: row['attempts']! as int,
      nextAttemptAt: optionalDate(row['next_attempt_at']),
    );
  }
}
