import 'dart:convert'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:http/http.dart'; import '../../../Helper/Logger.dart'; import '../../../Model/Response/Tenants/Tenantinforesponse.dart'; class TenantsProvider { static const cacheKey = 'TenantCache'; final cacheManager = DefaultCacheManager(); Future getTenantInfo(String urlData) async { TenantInfo? tenantInfo; logger.i('TenantInfo URL data: ${urlData}'); logger.i('TenantInfo URL data: $urlData'); // 👈 Add this here try { /// 1. Attempt to load from cache first final fileInfo = await cacheManager.getFileFromCache(cacheKey); String? cachedData; if (fileInfo != null && fileInfo.file.existsSync()) { cachedData = await fileInfo.file.readAsString(); final parsedJson = json.decode(cachedData); tenantInfo = TenantInfo.fromJson(parsedJson); logger.i("......Loaded data from cache......"); } /// 2.Always make a request to check for updates final response = await get(Uri.parse(urlData), headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }); if (response.statusCode == 200) { final freshData = response.body; /// Compare with cached data (optional optimization: hash/ETag/updatedAt) if (cachedData == null || freshData != cachedData) { logger.i("......Updating TenantDetails cache with fresh API data......."); /// Update the cache with fresh data await cacheManager.putFile( cacheKey, response.bodyBytes, fileExtension: 'json', key: cacheKey, ); final parsedJson = json.decode(freshData); tenantInfo = TenantInfo.fromJson(parsedJson); } else { logger.i(".........Tenant Details API data is same as cache, no update required.........."); } } else { logger.w("Tenant Details API responded with status code: ${response.statusCode}"); } } catch (e) { logger.e("Error fetching customer deals: $e"); } return tenantInfo; } }