import 'package:autos/core/constants/api_endpoints.dart';
import 'package:autos/data/models/product_model.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/product.dart';
import 'package:flutter/material.dart';

abstract class ProductRepository {
  Future<List<ProductEntity>> getProducts(String userId);
}

class ProductRepositoryImpl implements ProductRepository {
  final ApiService apiService;

  ProductRepositoryImpl(this.apiService);

  @override
  Future<List<ProductEntity>> getProducts(String userId) async {
    try {
      final url = '${ApiEndpoints.product}$userId';

      /// ✅ DEBUG PRINTS
      debugPrint("🌍 PRODUCT API HIT");
      debugPrint("➡️ URL: $url");

      final response = await apiService.get(url);

      debugPrint("✅ RAW PRODUCT API RESPONSE:");
      debugPrint(response.data.toString());

      /// ✅ SAFETY: If backend returns null → return empty list
      if (response.data == null) {
        debugPrint("⚠️ PRODUCT API RETURNED NULL → using empty list");
        return [];
      }

      /// ✅ SAFETY: Ensure response is really a List
      if (response.data is! List) {
        debugPrint("⚠️ PRODUCT API RETURNED NON-LIST DATA");
        return [];
      }

      final List data = response.data as List;

      debugPrint("✅ PARSED PRODUCT COUNT: ${data.length}");

      /// ✅ EMPTY LIST IS PERFECTLY VALID
      if (data.isEmpty) {
        debugPrint("ℹ️ NO PRODUCTS FOUND (EMPTY LIST)");
        return [];
      }

      /// ✅ SAFE MODEL PARSING
      return data
          .map((e) => ProductModel.fromJson(e))
          .toList();
    } catch (e, st) {
      debugPrint("❌ PRODUCT API REAL ERROR:");
      debugPrint(e.toString());
      debugPrint(st.toString());

      /// ✅ ONLY THROW FOR REAL FAILURES
      throw Exception("Products fetch error: $e");
    }
  }
}
