import 'job.dart';

enum DiscountType { percentage, fixed }

extension DiscountTypeX on DiscountType {
  String get value => name;
  String get label => this == DiscountType.percentage ? 'Yüzde (%)' : 'Sabit Tutar (TL)';
}

class ClinicDiscount {
  const ClinicDiscount({
    required this.id,
    required this.labTenantId,
    this.clinicTenantId,
    this.clinicName,
    this.prostheticType,
    required this.discountType,
    required this.discountValue,
    this.minQuantity = 0,
    required this.isActive,
    this.notes,
  });

  final String id;
  final String labTenantId;
  final String? clinicTenantId;   // null = tüm klinikler
  final String? clinicName;
  final String? prostheticType;   // null = tüm ürün tipleri
  final DiscountType discountType;
  final double discountValue;
  final int minQuantity;          // 0 = minimum yok
  final bool isActive;
  final String? notes;

  bool get appliesToAll => clinicTenantId == null || clinicTenantId!.isEmpty;
  bool get appliesToAllTypes => prostheticType == null || prostheticType!.isEmpty;

  String get displayValue => discountType == DiscountType.percentage
      ? '%${discountValue.toStringAsFixed(discountValue % 1 == 0 ? 0 : 1)}'
      : '${discountValue.toStringAsFixed(2)} TL';

  String get prostheticLabel {
    if (appliesToAllTypes) return 'Tüm Türler';
    return ProstheticType.values
        .firstWhere((e) => e.value == prostheticType,
            orElse: () => ProstheticType.diger)
        .label;
  }

  factory ClinicDiscount.fromJson(Map<String, dynamic> j) {
    final expand = j['expand'] as Map<String, dynamic>?;
    final clinicExp = expand?['clinic_tenant_id'] as Map<String, dynamic>?;
    final dt = j['discount_type'] as String? ?? 'percentage';
    final pt = j['prosthetic_type'] as String?;
    return ClinicDiscount(
      id: j['id'] as String,
      labTenantId: j['lab_tenant_id'] as String,
      clinicTenantId: j['clinic_tenant_id'] as String?,
      clinicName: clinicExp?['company_name'] as String?,
      prostheticType: (pt == null || pt.isEmpty) ? null : pt,
      discountType: dt == 'fixed' ? DiscountType.fixed : DiscountType.percentage,
      discountValue: (j['discount_value'] as num?)?.toDouble() ?? 0,
      minQuantity: (j['min_quantity'] as num?)?.toInt() ?? 0,
      isActive: j['is_active'] as bool? ?? true,
      notes: j['notes'] as String?,
    );
  }
}
