/// Payments Provider
///
/// Riverpod providers for managing payments state.
library;

import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/core/network/dio_client.dart';
import 'package:worker/features/orders/data/datasources/payment_remote_datasource.dart';
import 'package:worker/features/orders/data/repositories/payment_repository_impl.dart';
import 'package:worker/features/orders/domain/entities/payment.dart';
import 'package:worker/features/orders/domain/repositories/payment_repository.dart';

part 'payments_provider.g.dart';

/// Payment Repository Provider
@riverpod
Future<PaymentRepository> paymentRepository(Ref ref) async {
  final dioClient = await ref.watch(dioClientProvider.future);
  final remoteDataSource = PaymentRemoteDataSource(dioClient);
  return PaymentRepositoryImpl(remoteDataSource);
}

/// Payments Provider
///
/// Provides list of all payments from repository.
@riverpod
class Payments extends _$Payments {
  @override
  Future<List<Payment>> build() async {
    try {
      final repository = await ref.read(paymentRepositoryProvider.future);
      final payments = await repository.getPaymentsList(
        limitStart: 0,
        limitPageLength: 0, // 0 = get all
      );
      // Sort by posting date (newest first)
      payments.sort((a, b) => b.postingDate.compareTo(a.postingDate));
      return payments;
    } catch (e) {
      throw Exception('Failed to load payments: $e');
    }
  }

  /// Refresh payments
  Future<void> refresh() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      final repository = await ref.read(paymentRepositoryProvider.future);
      final payments = await repository.getPaymentsList(
        limitStart: 0,
        limitPageLength: 0,
      );
      // Sort by posting date (newest first)
      payments.sort((a, b) => b.postingDate.compareTo(a.postingDate));
      return payments;
    });
  }
}

/// Payment Detail Provider
///
/// Provides payment detail by ID.
@riverpod
Future<Payment> paymentDetail(Ref ref, String name) async {
  final repository = await ref.watch(paymentRepositoryProvider.future);
  return await repository.getPaymentDetail(name);
}
