import '../../domain/models/grocery_item.dart';
import '../../domain/repositories/grocery_repository.dart';

class GroceryRepositoryImpl implements GroceryRepository {
  final List<GroceryItem> _history = [];

  // Mock product database — replace with a real API later.
  final Map<String, GroceryItem> _mockDb = {
    '5901234123457': GroceryItem(
      barcode: '5901234123457',
      name: 'Organic Whole Milk',
      brand: 'Green Valley',
      category: 'Dairy',
      price: 4.99,
      description: 'Fresh organic whole milk, 1 gallon. Sourced from pasture-raised cows.',
    ),
    '4006381333931': GroceryItem(
      barcode: '4006381333931',
      name: 'Sourdough Bread',
      brand: 'Baker\'s Best',
      category: 'Bakery',
      price: 3.49,
      description: 'Artisan sourdough bread, freshly baked with a crispy crust.',
    ),
    '0011110838001': GroceryItem(
      barcode: '0011110838001',
      name: 'Free Range Eggs',
      brand: 'Farm Fresh',
      category: 'Eggs',
      price: 5.29,
      description: 'One dozen large free-range eggs.',
    ),
  };

  @override
  Future<GroceryItem?> lookupBarcode(String barcode) async {
    // Simulate network delay
    await Future.delayed(const Duration(milliseconds: 500));

    if (_mockDb.containsKey(barcode)) {
      return GroceryItem(
        barcode: _mockDb[barcode]!.barcode,
        name: _mockDb[barcode]!.name,
        brand: _mockDb[barcode]!.brand,
        category: _mockDb[barcode]!.category,
        imageUrl: _mockDb[barcode]!.imageUrl,
        price: _mockDb[barcode]!.price,
        description: _mockDb[barcode]!.description,
      );
    }

    // Return a generic item for unknown barcodes
    return GroceryItem(
      barcode: barcode,
      name: 'Unknown Product',
      brand: 'Unknown',
      category: 'Other',
      description: 'No product information found for barcode: $barcode',
    );
  }

  @override
  List<GroceryItem> getScanHistory() => List.unmodifiable(_history);

  @override
  void addToHistory(GroceryItem item) {
    _history.insert(0, item);
  }

  @override
  void clearHistory() {
    _history.clear();
  }
}