part of '../analytic.dart';

@freezed
class ProductAnalytic with _$ProductAnalytic {
  const ProductAnalytic._();

  const factory ProductAnalytic({
    required String organizationId,
    required String outletId,
    required DateTime dateFrom,
    required DateTime dateTo,
    required List<ProductAnalyticItem> data,
  }) = _ProductAnalytic;

  factory ProductAnalytic.empty() => ProductAnalytic(
    organizationId: '',
    outletId: '',
    dateFrom: DateTime.now(),
    dateTo: DateTime.now(),
    data: const [],
  );

  ProductAnalyticItem get bestProduct {
    if (data.isEmpty) {
      return ProductAnalyticItem.empty();
    }

    return data.first;
  }

  List<ProductAnalyticCategoryItem> get categories {
    final Map<String, ProductAnalyticCategoryItem> categoryMap = {};

    for (final product in data) {
      final key = product.categoryName;

      if (categoryMap.containsKey(key)) {
        final existing = categoryMap[key]!;
        categoryMap[key] = existing.copyWith(
          productCount: existing.productCount + 1,
          totalRevenue: existing.totalRevenue + product.revenue,
        );
      } else {
        categoryMap[key] = ProductAnalyticCategoryItem(
          categoryName: product.categoryName,
          productCount: 1,
          totalRevenue: product.revenue,
        );
      }
    }

    final categorySummary = categoryMap.values.toList()
      ..sort((a, b) => b.totalRevenue.compareTo(a.totalRevenue));

    return categorySummary;
  }
}

@freezed
class ProductAnalyticItem with _$ProductAnalyticItem {
  const factory ProductAnalyticItem({
    required String productId,
    required String productName,
    required String categoryId,
    required String categoryName,
    required int quantitySold,
    required int revenue,
    required double averagePrice,
    required int orderCount,
  }) = _ProductAnalyticItem;

  factory ProductAnalyticItem.empty() => const ProductAnalyticItem(
    productId: '',
    productName: '',
    categoryId: '',
    categoryName: '',
    quantitySold: 0,
    revenue: 0,
    averagePrice: 0.0,
    orderCount: 0,
  );
}

@freezed
class ProductAnalyticCategoryItem with _$ProductAnalyticCategoryItem {
  const factory ProductAnalyticCategoryItem({
    required String categoryName,
    required int productCount,
    required int totalRevenue,
  }) = _ProductAnalyticCategoryItem;

  // ignore: prefer_const_constructors
  factory ProductAnalyticCategoryItem.empty() => ProductAnalyticCategoryItem(
    categoryName: '',
    productCount: 0,
    totalRevenue: 0,
  );
}
