import 'package:json_annotation/json_annotation.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';

import '../../domain/entities/inventory_summary.dart';
import '../../domain/entities/inventory_summary_list_result.dart';
import 'inventory_common_dtos.dart';

part 'inventory_summary_response.g.dart';

@JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true)
class InventorySummaryResponse {
  const InventorySummaryResponse({
    List<InventorySummaryItemDto>? items,
    this.page = 1,
    this.pageSize = 0,
    this.total = 0,
    this.lastRefreshedAt,
  }) : items = items ?? const [];

  @JsonKey(defaultValue: <InventorySummaryItemDto>[])
  final List<InventorySummaryItemDto> items;
  final int page;
  final int pageSize;
  final int total;
  final DateTime? lastRefreshedAt;

  factory InventorySummaryResponse.fromJson(Map<String, dynamic> json) =>
      _$InventorySummaryResponseFromJson(json);

  Map<String, dynamic> toJson() => _$InventorySummaryResponseToJson(this);

  InventorySummaryListResult toEntity() {
    final summaries = items
        .map((item) => item.toEntity())
        .toList(growable: false);
    final paginated = PaginatedResult<InventorySummary>(
      items: summaries,
      page: page,
      pageSize: pageSize,
      total: total,
    );
    return InventorySummaryListResult(
      result: paginated,
      lastRefreshedAt:
          lastRefreshedAt ??
          (summaries.isNotEmpty ? summaries.first.lastRefreshedAt : null),
    );
  }
}

@JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true)
class InventorySummaryItemDto {
  const InventorySummaryItemDto({
    required this.product,
    required this.totalQuantity,
    List<InventoryWarehouseBalanceDto>? warehouseBalances,
    this.recentEvent,
    this.updatedAt,
    this.lastRefreshedAt,
  }) : warehouseBalances = warehouseBalances ?? const [];

  final InventoryProductDto product;
  @JsonKey(fromJson: _parseQuantity)
  final int totalQuantity;
  @JsonKey(defaultValue: <InventoryWarehouseBalanceDto>[])
  final List<InventoryWarehouseBalanceDto> warehouseBalances;
  final InventoryEventDto? recentEvent;
  final DateTime? updatedAt;
  final DateTime? lastRefreshedAt;

  factory InventorySummaryItemDto.fromJson(Map<String, dynamic> json) =>
      _$InventorySummaryItemDtoFromJson(json);

  Map<String, dynamic> toJson() => _$InventorySummaryItemDtoToJson(this);

  InventorySummary toEntity() {
    final balances = warehouseBalances
        .map((balance) => balance.toEntity())
        .toList(growable: false);
    return InventorySummary(
      product: product.toEntity(),
      totalQuantity: totalQuantity,
      warehouseBalances: balances,
      recentEvent: recentEvent?.toEntity(),
      updatedAt: updatedAt,
      lastRefreshedAt: lastRefreshedAt,
    );
  }
}

int _parseQuantity(dynamic value) {
  if (value == null) {
    return 0;
  }
  if (value is int) {
    return value;
  }
  if (value is num) {
    return value.round();
  }
  if (value is String) {
    final sanitized = value.replaceAll(',', '').trim();
    if (sanitized.isEmpty) {
      return 0;
    }
    final parsed = num.tryParse(sanitized);
    if (parsed != null) {
      return parsed.round();
    }
  }
  return 0;
}
