import 'package:json_annotation/json_annotation.dart';

import '../../domain/entities/inventory_detail.dart';
import 'inventory_common_dtos.dart';

part 'inventory_detail_response.g.dart';

@JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true)
class InventoryDetailResponse {
  const InventoryDetailResponse({required this.data});

  final InventoryDetailDataDto data;

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

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

  InventoryDetail toEntity() => data.toEntity();
}

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

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

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

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

  InventoryDetail toEntity() => InventoryDetail(
    product: product.toEntity(),
    totalQuantity: totalQuantity,
    warehouseBalances: warehouseBalances
        .map((balance) => balance.toEntity())
        .toList(growable: false),
    recentEvents: recentEvents
        .map((event) => event.toEntity())
        .toList(growable: false),
    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;
}
