import 'dart:convert';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:http/http.dart';
import 'package:http/http.dart' as http;

import '../../../Helper/Logger.dart';
import '../../../Model/Request/products/update_product.dart';
import '../../../Model/Response/products/product_info.dart';
import '../../../Model/Response/products/product_response.dart';
import '../../../Model/Response/products/product_update_response.dart';



class GetProductsProvider {

  static const cacheKey = 'productCache';
  final cacheManager = DefaultCacheManager();

  Future<GetProducts?> getProducts(String urlData) async {
    GetProducts? getProducts;
    logger.i('Get all products url data : $urlData');

    try {
      // 1. Cache first
      final fileInfo = await cacheManager.getFileFromCache(cacheKey);
      String? cachedData;
      if (fileInfo != null && fileInfo.file.existsSync()) {
        cachedData = await fileInfo.file.readAsString();
        getProducts = GetProducts.fromJson(json.decode(cachedData));
        logger.i("Loaded data from cache");
      }

      // 2. Always hit the network
      final response = await http.get(
        Uri.parse(urlData),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      );

      if (response.statusCode == 200) {
        final freshData = response.body;

        print(response);

        if (cachedData == null || freshData != cachedData) {
          logger.i("Updating cache with fresh data");
          await cacheManager.putFile(
            cacheKey,
            response.bodyBytes,
            fileExtension: 'json',
            key: cacheKey,
          );
          getProducts = GetProducts.fromJson(json.decode(freshData));
        } else {
          logger.i("Cache and API data identical – no update");
        }
      } else {
        logger.w("API status: ${response.statusCode}");
      }
    } catch (e) {
      logger.e("Error fetching products: $e");
    }

    return getProducts;
  }

  Future<ProductUpdateResponse?> updateProducts(
      ProductUpdateRequest data, String urldata) async {
    ProductUpdateResponse? productUpdateResponse;

    try {
      final url = Uri.parse(urldata);
      final jsonBody = json.encode(data.toJson());

      // 🔥 THIS IS WHAT YOU WANT TO SEE 🔥
      print('🚀 SENDING PUT REQUEST');
      print('URL: $url');
      print('HEADERS: ${{
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      }}');
      print('BODY → ${jsonBody}'); // ← Exact JSON being sent
      print('PRETTY BODY → ${const JsonEncoder.withIndent('  ').convert(data.toJson())}');

      final response = await put(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: jsonBody,
      );

      print('✅ RESPONSE: ${response.statusCode}');
      print('Response Body: ${response.body}');

      final parsedJson = json.decode(response.body);
      productUpdateResponse = ProductUpdateResponse.fromJson(parsedJson);

      print('Parsed → $productUpdateResponse');

    } catch (e) {
      print('❌ ERROR: $e');
    }

    return productUpdateResponse;
  }


  Future<ProductDetailResponse?> getProductDetail(String urldata,) async {
    logger.i('UrlData for product Details : ${urldata}');
    ProductDetailResponse? getProductDetailResponse;
    try {
      final url = Uri.parse(urldata);

      final response = await get(url, headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      });
      logger.i('Product Response ${response.body}');
      logger.i('Get product Details Response${urldata.toString()}');
      Map<String, dynamic> parsedJson = json.decode(response.body.toString());

      getProductDetailResponse = ProductDetailResponse.fromJson(parsedJson);
    } catch (e) {
      logger.i(e.toString());
      logger.i('error in productDetails${e.toString()}');
      logger.i("error");
    }
    return getProductDetailResponse;
  }


}