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

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

  PocketBase get _pb => PocketBaseClient.instance.pb;

  Future<List<Connection>> listConnections(String labTenantId) async {
    final result = await _pb.collection('connections').getList(
      filter: 'lab_tenant_id = "$labTenantId"',
      expand: 'clinic_tenant_id,lab_tenant_id',
      perPage: 100,
    );
    return (result.items.map((r) => Connection.fromJson(r.toJson())).toList()
      ..sort((a, b) => (b.dateCreated ?? '').compareTo(a.dateCreated ?? '')));
  }

  Future<Connection> respondToRequest({
    required String connectionId,
    required bool approve,
  }) async {
    final record = await _pb.collection('connections').update(connectionId, body: {
      'status': approve ? 'approved' : 'rejected',
    });
    return Connection.fromJson(record.toJson());
  }
}
