import 'package:krow_data_connect/krow_data_connect.dart' as dc;
import 'package:krow_data_connect/krow_data_connect.dart';
import 'package:krow_domain/krow_domain.dart';

import '../../domain/repositories/payments_repository.dart';

class PaymentsRepositoryImpl
    implements PaymentsRepository {

  PaymentsRepositoryImpl() : _service = DataConnectService.instance;
  final DataConnectService _service;

  @override
  Future<PaymentSummary> getPaymentSummary() async {
    return _service.run(() async {
      final String currentStaffId = await _service.getStaffId();

      // Fetch recent payments with a limit
      final response = await _service.connector.listRecentPaymentsByStaffId(
          staffId: currentStaffId,
      ).limit(100).execute();

      final List<dc.ListRecentPaymentsByStaffIdRecentPayments> payments = response.data.recentPayments;

      double weekly = 0;
      double monthly = 0;
      double pending = 0;
      double total = 0;

      final DateTime now = DateTime.now();
      final DateTime startOfWeek = now.subtract(const Duration(days: 7));
      final DateTime startOfMonth = DateTime(now.year, now.month, 1);

      for (final dc.ListRecentPaymentsByStaffIdRecentPayments p in payments) {
          final DateTime? date = _service.toDateTime(p.invoice.issueDate) ?? _service.toDateTime(p.createdAt);
          final double amount = p.invoice.amount;
          final String? status = p.status?.stringValue;

          if (status == 'PENDING') {
              pending += amount;
          } else if (status == 'PAID') {
              total += amount;
              if (date != null) {
                  if (date.isAfter(startOfWeek)) weekly += amount;
                  if (date.isAfter(startOfMonth)) monthly += amount;
              }
          }
      }

      return PaymentSummary(
        weeklyEarnings: weekly,
        monthlyEarnings: monthly,
        pendingEarnings: pending,
        totalEarnings: total,
      );
    });
  }

  @override
  Future<List<StaffPayment>> getPaymentHistory(String period) async {
    return _service.run(() async {
      final String currentStaffId = await _service.getStaffId();
      
      final response = await _service.connector
          .listRecentPaymentsByStaffId(staffId: currentStaffId)
          .execute();

      return response.data.recentPayments.map((dc.ListRecentPaymentsByStaffIdRecentPayments payment) {
        return StaffPayment(
          id: payment.id,
          staffId: payment.staffId,
          assignmentId: payment.applicationId,
          amount: payment.invoice.amount,
          status: PaymentAdapter.toPaymentStatus(payment.status?.stringValue ?? 'UNKNOWN'),
          paidAt: _service.toDateTime(payment.invoice.issueDate),
        );
      }).toList();
    });
  }
}

