import 'package:uuid/uuid.dart';
import 'package:barber_app/core/database/database_service.dart';
import 'package:barber_app/features/products/data/models/product_model.dart';

class ProductRepository {
  final _uuid = const Uuid();

  String? get _currentUserId => DatabaseService.getCurrentUserId();

  // Criar produto
  Future<ProductModel?> createProduct({
    required String name,
    required String category,
    required int quantity,
    required double purchasePrice,
    required double salePrice,
    int minStock = 5,
    String? imagePath,
  }) async {
    if (_currentUserId == null) return null;

    final product = ProductModel(
      id: _uuid.v4(),
      userId: _currentUserId!,
      name: name.trim(),
      category: category,
      quantity: quantity,
      purchasePrice: purchasePrice,
      salePrice: salePrice,
      minStock: minStock,
      imagePath: imagePath,
    );

    await DatabaseService.productsBoxInstance.put(product.id, product);
    return product;
  }

  // Listar todos os produtos
  List<ProductModel> getAllProducts() {
    if (_currentUserId == null) return [];
    return DatabaseService.productsBoxInstance.values
        .where((p) => p.userId == _currentUserId)
        .toList()
      ..sort((a, b) => a.name.compareTo(b.name));
  }

  // Produtos por categoria
  List<ProductModel> getProductsByCategory(String category) {
    return getAllProducts().where((p) => p.category == category).toList();
  }

  // Produtos com estoque baixo
  List<ProductModel> getLowStockProducts() {
    return getAllProducts().where((p) => p.isLowStock).toList();
  }

  // Atualizar produto
  Future<ProductModel?> updateProduct(ProductModel product) async {
    await DatabaseService.productsBoxInstance.put(product.id, product);
    return product;
  }

  // Atualizar quantidade
  Future<ProductModel?> updateQuantity(String id, int newQuantity) async {
    final product = DatabaseService.productsBoxInstance.get(id);
    if (product == null) return null;

    final updated = product.copyWith(quantity: newQuantity);
    await DatabaseService.productsBoxInstance.put(id, updated);
    return updated;
  }

  // Deletar produto
  Future<void> deleteProduct(String id) async {
    await DatabaseService.productsBoxInstance.delete(id);
  }

  // Buscar por ID
  ProductModel? getProductById(String id) {
    return DatabaseService.productsBoxInstance.get(id);
  }

  // Total em estoque (valor de compra)
  double getTotalStockValue() {
    return getAllProducts().fold(
      0.0,
      (sum, p) => sum + (p.purchasePrice * p.quantity),
    );
  }
}
