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

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

  PocketBase get _pb => PocketBaseClient.instance.pb;

  Future<List<FinanceEntry>> listEntries(
    String tenantId, {
    String? status,
    int page = 1,
    int limit = 30,
  }) async {
    final filterParts = ['tenant_id = "$tenantId"', 'type = "receivable"'];
    if (status != null) filterParts.add('status = "$status"');

    final result = await _pb.collection('finance_entries').getList(
      page: page,
      perPage: limit,
      filter: filterParts.join(' && '),
      expand: 'job_id',
    );
    return (result.items.map((r) => FinanceEntry.fromJson(r.toJson())).toList()
      ..sort((a, b) => (b.dateCreated ?? '').compareTo(a.dateCreated ?? '')));
  }

  Future<Map<String, double>> summary(String tenantId) async {
    final all = await listEntries(tenantId, limit: 200);
    double pending = 0, paid = 0;
    for (final e in all) {
      if (e.status == FinanceStatus.pending) {
        pending += e.amount;
      } else {
        paid += e.amount;
      }
    }
    return {'pending': pending, 'paid': paid};
  }
}
