import 'package:logging/logging.dart';

import 'package:uuid/uuid.dart';

import 'package:pshared/api/requests/payment/initiate.dart';
import 'package:pshared/api/responses/payment/payment.dart';
import 'package:pshared/api/responses/payment/payments.dart';
import 'package:pshared/data/mapper/payment/payment_response.dart';
import 'package:pshared/models/payment/page.dart';
import 'package:pshared/models/payment/payment.dart';
import 'package:pshared/service/authorization/service.dart';
import 'package:pshared/service/services.dart';
import 'package:pshared/utils/http/params.dart';

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

  static Future<PaymentPage> listPage(
    String organizationRef, {
    int? limit,
    String? cursor,
    String? quotationRef,
    DateTime? createdFrom,
    DateTime? createdTo,
    List<String>? states,
  }) async {
    _logger.fine('Listing payments for organization $organizationRef');
    final queryParams = <String, String>{};
    if (quotationRef != null && quotationRef.isNotEmpty) {
      queryParams['quotation_ref'] = quotationRef;
    }
    if (createdFrom != null) {
      queryParams['created_from'] = createdFrom.toUtc().toIso8601String();
    }
    if (createdTo != null) {
      queryParams['created_to'] = createdTo.toUtc().toIso8601String();
    }
    if (states != null && states.isNotEmpty) {
      queryParams['state'] = states.join(',');
    }

    final url = cursorParamsToUriString(
      path: '/$organizationRef',
      limit: limit,
      cursor: cursor,
      queryParams: queryParams,
    );
    final response = await AuthorizationService.getGETResponse(
      _objectType,
      url,
    );
    final parsed = PaymentsResponse.fromJson(response);
    final payments = parsed.payments
        .map((payment) => payment.toDomain())
        .toList();
    return PaymentPage(items: payments, nextCursor: parsed.nextCursor);
  }

  static Future<List<Payment>> list(
    String organizationRef, {
    int? limit,
    String? cursor,
    String? quotationRef,
    DateTime? createdFrom,
    DateTime? createdTo,
    List<String>? states,
  }) async {
    final page = await listPage(
      organizationRef,
      limit: limit,
      cursor: cursor,
      quotationRef: quotationRef,
      createdFrom: createdFrom,
      createdTo: createdTo,
      states: states,
    );
    return page.items;
  }

  static Future<Payment> pay(
    String organizationRef,
    String quotationRef, {
    String? idempotencyKey,
    String? clientPaymentRef,
    Map<String, String>? metadata,
  }) async {
    _logger.fine(
      'Executing payment for quotation $quotationRef in $organizationRef',
    );
    final request = InitiatePaymentRequest(
      idempotencyKey: idempotencyKey ?? Uuid().v4(),
      quoteRef: quotationRef,
      clientPaymentRef: clientPaymentRef,
      metadata: metadata,
    );
    final response = await AuthorizationService.getPOSTResponse(
      _objectType,
      '/by-quote/$organizationRef',
      request.toJson(),
    );
    return PaymentResponse.fromJson(response).payment.toDomain();
  }
}
