import 'package:pocketbase/pocketbase.dart';
import '../../../core/api/pocketbase_client.dart';
import '../../../models/clinic_discount.dart';

class DiscountRepository {
  DiscountRepository._();
  static final instance = DiscountRepository._();

  PocketBase get _pb => PocketBaseClient.instance.pb;

  Future<List<ClinicDiscount>> listDiscounts(String labTenantId) async {
    final result = await _pb.collection('clinic_discounts').getList(
      filter: 'lab_tenant_id = "$labTenantId"',
      expand: 'clinic_tenant_id',
      perPage: 200,
    );
    final list = result.items
        .map((r) => ClinicDiscount.fromJson(r.toJson()))
        .toList();
    list.sort((a, b) {
      // Active first, then by clinic name
      if (a.isActive != b.isActive) return a.isActive ? -1 : 1;
      final ca = a.clinicName ?? '';
      final cb = b.clinicName ?? '';
      return ca.compareTo(cb);
    });
    return list;
  }

  Future<ClinicDiscount> createDiscount({
    required String labTenantId,
    String? clinicTenantId,
    String? prostheticType,
    required DiscountType discountType,
    required double discountValue,
    int minQuantity = 0,
    bool isActive = true,
    String? notes,
  }) async {
    final body = <String, dynamic>{
      'lab_tenant_id': labTenantId,
      'discount_type': discountType.value,
      'discount_value': discountValue,
      'is_active': isActive,
    };
    if (clinicTenantId != null && clinicTenantId.isNotEmpty) {
      body['clinic_tenant_id'] = clinicTenantId;
    }
    if (prostheticType != null && prostheticType.isNotEmpty) {
      body['prosthetic_type'] = prostheticType;
    }
    if (minQuantity > 0) body['min_quantity'] = minQuantity;
    if (notes != null && notes.isNotEmpty) body['notes'] = notes;

    final record = await _pb.collection('clinic_discounts').create(
      body: body,
      expand: 'clinic_tenant_id',
    );
    return ClinicDiscount.fromJson(record.toJson());
  }

  Future<ClinicDiscount> updateDiscount(
    String id, {
    String? clinicTenantId,
    String? prostheticType,
    DiscountType? discountType,
    double? discountValue,
    int? minQuantity,
    bool? isActive,
    String? notes,
  }) async {
    final body = <String, dynamic>{};
    if (clinicTenantId != null) body['clinic_tenant_id'] = clinicTenantId.isEmpty ? null : clinicTenantId;
    if (prostheticType != null) body['prosthetic_type'] = prostheticType.isEmpty ? '' : prostheticType;
    if (discountType != null) body['discount_type'] = discountType.value;
    if (discountValue != null) body['discount_value'] = discountValue;
    if (minQuantity != null) body['min_quantity'] = minQuantity;
    if (isActive != null) body['is_active'] = isActive;
    if (notes != null) body['notes'] = notes;

    final record = await _pb.collection('clinic_discounts').update(
      id,
      body: body,
      expand: 'clinic_tenant_id',
    );
    return ClinicDiscount.fromJson(record.toJson());
  }

  Future<void> deleteDiscount(String id) async {
    await _pb.collection('clinic_discounts').delete(id);
  }
}
