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

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

  PocketBase get _pb => PocketBaseClient.instance.pb;

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

  Future<Connection> requestConnection({
    required String clinicTenantId,
    required String labTenantId,
  }) async {
    final record = await _pb.collection('connections').create(body: {
      'clinic_tenant_id': clinicTenantId,
      'lab_tenant_id': labTenantId,
      'status': 'pending',
    });
    return Connection.fromJson(record.toJson());
  }

  Future<List<Tenant>> searchLabs({
    String query = '',
    String? city,
  }) async {
    final normalizedQuery = query.trim().replaceAll('"', '\\"');
    final normalizedCity = (city ?? '').trim().replaceAll('"', '\\"');

    final filterParts = ['kind = "lab"'];
    if (normalizedQuery.isNotEmpty) {
      filterParts.add(
        '(company_name ~ "$normalizedQuery" || city ~ "$normalizedQuery" || district ~ "$normalizedQuery")',
      );
    } else if (normalizedCity.isNotEmpty) {
      filterParts.add('city = "$normalizedCity"');
    }

    final result = await _pb.collection('tenants').getList(
          filter: filterParts.join(' && '),
          perPage: 100,
        );
    return result.items.map((r) => Tenant.fromJson(r.toJson())).toList();
  }
}
