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

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

  PocketBase get _pb => PocketBaseClient.instance.pb;

  Future<List<ProstheticProduct>> listProducts(
    String labTenantId, {
    bool? isActive,
  }) async {
    final filterParts = ['lab_tenant_id = "$labTenantId"'];
    if (isActive != null) filterParts.add('is_active = $isActive');

    final result = await _pb.collection('prosthetic_products').getList(
      filter: filterParts.join(' && '),
      perPage: 200,
    );
    return (result.items.map((r) => ProstheticProduct.fromJson(r.toJson())).toList()
      ..sort((a, b) => a.name.compareTo(b.name)));
  }

  Future<ProstheticProduct> createProduct(ProstheticProduct product) async {
    final record = await _pb.collection('prosthetic_products').create(body: product.toJson());
    return ProstheticProduct.fromJson(record.toJson());
  }

  Future<ProstheticProduct> updateProduct(String id, Map<String, dynamic> patch) async {
    final record = await _pb.collection('prosthetic_products').update(id, body: patch);
    return ProstheticProduct.fromJson(record.toJson());
  }

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