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

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

  PocketBase get _pb => PocketBaseClient.instance.pb;

  Future<List<Patient>> listPatients(
    String tenantId, {
    String? search,
    int page = 1,
    int limit = 30,
  }) async {
    final filterParts = ['tenant_id = "$tenantId"'];
    if (search != null && search.isNotEmpty) {
      filterParts.add(
        '(patient_code ~ "$search" || first_name ~ "$search" || last_name ~ "$search")',
      );
    }

    final result = await _pb.collection('patients').getList(
      page: page,
      perPage: limit,
      filter: filterParts.join(' && '),
    );
    return (result.items.map((r) => Patient.fromJson(r.toJson())).toList()
      ..sort((a, b) => a.patientCode.compareTo(b.patientCode)));
  }

  Future<Patient> getPatient(String patientId) async {
    final record = await _pb.collection('patients').getOne(patientId);
    return Patient.fromJson(record.toJson());
  }

  Future<Patient> createPatient({
    required String tenantId,
    required String patientCode,
    String? firstName,
    String? lastName,
    String? birthDate,
    String? phone,
    String? notes,
  }) async {
    final record = await _pb.collection('patients').create(body: {
      'tenant_id': tenantId,
      'patient_code': patientCode,
      if (firstName != null) 'first_name': firstName,
      if (lastName != null) 'last_name': lastName,
      if (birthDate != null) 'birth_date': birthDate,
      if (phone != null) 'phone': phone,
      if (notes != null) 'notes': notes,
    });
    return Patient.fromJson(record.toJson());
  }

  Future<Patient> updatePatient(String patientId, Map<String, dynamic> patch) async {
    final record = await _pb.collection('patients').update(patientId, body: patch);
    return Patient.fromJson(record.toJson());
  }

  Future<void> deletePatient(String patientId) async {
    await _pb.collection('patients').delete(patientId);
  }
}
