import 'package:autos/core/constants/api_endpoints.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class TokenRepository {
  final ApiService apiService;
  final _storage = const FlutterSecureStorage();

  TokenRepository(this.apiService);

  static const _tokenKey = "turn14_token";
  static const _tokenTimeKey = "turn14_token_time";

  /// ✅ Get Valid Token (Auto Refresh If Expired)
  Future<String> getValidToken(String userId) async {
    final token = await _storage.read(key: _tokenKey);
    final time = await _storage.read(key: _tokenTimeKey);

    if (token != null && time != null) {
      final savedTime = DateTime.parse(time);
      final diff = DateTime.now().difference(savedTime);

      /// ✅ Token Valid for 50 minutes
      if (diff.inMinutes < 50) {
        return token;
      }
    }

    /// 🔄 Token Expired → Refresh
    return await _refreshToken(userId);
  }

  /// 🔄 Refresh Token API
  Future<String> _refreshToken(String userId) async {
    final response = await apiService.post(ApiEndpoints.getToken, {
      "userid": userId,
    });

    final data = response.data;
    final code = data["code"];
    final token = data["access_token"];

    if (code == "TOKEN_VALID" || code == "TOKEN_UPDATED") {
      // ✅ Save token and timestamp if updated, otherwise just use existing token
      if (code == "TOKEN_UPDATED") {
        await _storage.write(key: _tokenKey, value: token);
        await _storage.write(
          key: _tokenTimeKey,
          value: DateTime.now().toIso8601String(),
        );
      }
      return token;
    } else {
      throw Exception("Failed to get Turn14 token: ${data["message"]}");
    }
  }
}
