import 'package:logging/logging.dart';

import 'package:uuid/uuid.dart';

import 'package:pshared/api/requests/payment/initiate_payments.dart';
import 'package:pshared/api/requests/payment/quotes.dart';
import 'package:pshared/api/responses/payment/payments.dart';
import 'package:pshared/api/responses/payment/quotes.dart';
import 'package:pshared/data/mapper/payment/payment_response.dart';
import 'package:pshared/data/mapper/payment/quote/quotes.dart';
import 'package:pshared/models/payment/payment.dart';
import 'package:pshared/models/payment/quote/quotes.dart';
import 'package:pshared/service/authorization/service.dart';
import 'package:pshared/service/services.dart';

class MultiplePaymentsService {
  static final _logger = Logger('service.payment.multiple');
  static const String _objectType = Services.payments;

  static Future<PaymentQuotes> getQuotation(
    String organizationRef,
    QuotePaymentsRequest request,
  ) async {
    _logger.fine('Quoting multiple payments for organization $organizationRef');
    final response = await AuthorizationService.getPOSTResponse(
      _objectType,
      '/multiquote/$organizationRef',
      request.toJson(),
    );

    final parsed = PaymentQuotesResponse.fromJson(response);
    return parsed.quote.toDomain();
  }

  static Future<List<Payment>> payByQuote(
    String organizationRef,
    String quoteRef, {
    String? idempotencyKey,
    String? clientPaymentRef,
    Map<String, String>? metadata,
  }) async {
    _logger.fine(
      'Executing multiple payments for quote $quoteRef in $organizationRef',
    );
    final request = InitiatePaymentsRequest(
      idempotencyKey: idempotencyKey ?? const Uuid().v4(),
      quoteRef: quoteRef,
      clientPaymentRef: clientPaymentRef,
      metadata: metadata,
    );

    final response = await AuthorizationService.getPOSTResponse(
      _objectType,
      '/by-multiquote/$organizationRef',
      request.toJson(),
    );

    final parsed = PaymentsResponse.fromJson(response);
    return parsed.payments.map((payment) => payment.toDomain()).toList();
  }
}
