import 'package:hl_lieferservice/feature/cars/model/selection.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CarSelectionRepository {
  static String _keyDate(String userId) => 'car_selection_${userId}_date';
  static String _keyCarId(String userId) => 'car_selection_${userId}_car_id';
  static String _keyCarPlate(String userId) =>
      'car_selection_${userId}_car_plate';

  /// Returns the stored [CarSelection] for the given user, or null if nothing
  /// has been saved yet for that user.
  Future<CarSelection?> getSelection(String userId) async {
    final prefs = await SharedPreferences.getInstance();

    final dateString = prefs.getString(_keyDate(userId));
    final carId = prefs.getInt(_keyCarId(userId));
    final plate = prefs.getString(_keyCarPlate(userId));

    if (dateString == null || carId == null || plate == null) return null;

    return CarSelection(
      date: DateTime.parse(dateString),
      selectedCarId: carId,
      selectedCarPlate: plate,
    );
  }

  /// Persists the given [selection] for the given user locally on this device.
  Future<void> saveSelection(String userId, CarSelection selection) async {
    final prefs = await SharedPreferences.getInstance();

    await prefs.setString(_keyDate(userId), selection.date.toIso8601String());
    await prefs.setInt(_keyCarId(userId), selection.selectedCarId!);
    await prefs.setString(_keyCarPlate(userId), selection.selectedCarPlate!);
  }
}
