import 'package:logging/logging.dart';

import 'package:pshared/models/file/downloaded_file.dart';
import 'package:pshared/service/authorization/service.dart';
import 'package:pshared/service/services.dart';


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

  static Future<DownloadedFile> getOperationDocument(
    String organizationRef,
    String gatewayService,
    String operationRef,
    String paymentRef,
  ) async {
    final query = <String, String>{
      'gateway_service': gatewayService,
      'operation_ref': operationRef,
      'payment_ref': paymentRef,
    };
    final queryString = Uri(queryParameters: query).query;
    final url = '/documents/operation/$organizationRef?$queryString';
    _logger.fine(
      'Downloading operation document for operation $operationRef in gateway $gatewayService',
    );
    final response = await AuthorizationService.getGETBinaryResponse(
      _objectType,
      url,
    );
    final filename =
        _filenameFromDisposition(response.header('content-disposition')) ??
        'operation_$operationRef.pdf';
    final mimeType = response.header('content-type') ?? 'application/pdf';
    return DownloadedFile(
      bytes: response.bytes,
      filename: filename,
      mimeType: mimeType,
    );
  }

  static String? _filenameFromDisposition(String? disposition) {
    if (disposition == null || disposition.isEmpty) return null;
    final parts = disposition.split(';');
    for (final part in parts) {
      final trimmed = part.trim();
      if (trimmed.toLowerCase().startsWith('filename=')) {
        var value = trimmed.substring('filename='.length).trim();
        if (value.startsWith('"') && value.endsWith('"') && value.length > 1) {
          value = value.substring(1, value.length - 1);
        }
        if (value.isNotEmpty) {
          return value;
        }
      }
    }
    return null;
  }
}
