import 'package:hive_ce/hive.dart';

import 'package:worker/core/constants/storage_constants.dart';

part 'stock_level_model.g.dart';

/// Stock Level Model
///
/// Hive CE model for caching stock level data locally.
/// Maps to the 'stock_levels' table in the database.
///
/// Type ID: 3
@HiveType(typeId: HiveTypeIds.stockLevelModel)
class StockLevelModel extends HiveObject {
  StockLevelModel({
    required this.productId,
    required this.availableQty,
    required this.reservedQty,
    required this.orderedQty,
    required this.warehouseCode,
    required this.lastUpdated,
  });

  @HiveField(0)
  final String productId;

  @HiveField(1)
  final double availableQty;

  @HiveField(2)
  final double reservedQty;

  @HiveField(3)
  final double orderedQty;

  @HiveField(4)
  final String warehouseCode;

  @HiveField(5)
  final DateTime lastUpdated;

  factory StockLevelModel.fromJson(Map<String, dynamic> json) {
    return StockLevelModel(
      productId: json['product_id'] as String,
      availableQty: (json['available_qty'] as num).toDouble(),
      reservedQty: (json['reserved_qty'] as num).toDouble(),
      orderedQty: (json['ordered_qty'] as num).toDouble(),
      warehouseCode: json['warehouse_code'] as String,
      lastUpdated: DateTime.parse(json['last_updated'] as String),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'product_id': productId,
      'available_qty': availableQty,
      'reserved_qty': reservedQty,
      'ordered_qty': orderedQty,
      'warehouse_code': warehouseCode,
      'last_updated': lastUpdated.toIso8601String(),
    };
  }

  double get totalQty => availableQty + reservedQty + orderedQty;
  bool get inStock => availableQty > 0;

  StockLevelModel copyWith({
    String? productId,
    double? availableQty,
    double? reservedQty,
    double? orderedQty,
    String? warehouseCode,
    DateTime? lastUpdated,
  }) {
    return StockLevelModel(
      productId: productId ?? this.productId,
      availableQty: availableQty ?? this.availableQty,
      reservedQty: reservedQty ?? this.reservedQty,
      orderedQty: orderedQty ?? this.orderedQty,
      warehouseCode: warehouseCode ?? this.warehouseCode,
      lastUpdated: lastUpdated ?? this.lastUpdated,
    );
  }
}
