<?php

namespace MefisAssetBridgeCore\Api\Storage;

/**
 * S3StorageResponseParser - Parse AWS S3 XML error responses
 *
 * AWS S3 returns error responses in XML format:
 * <Error>
 *   <Code>...</Code>
 *   <Message>...</Message>
 *   <RequestId>...</RequestId>
 *   <HostId>...</HostId>
 * </Error>
 */
class S3StorageResponseParser
{
    /**
     * Parse AWS S3 XML error response
     *
     * @param string $xmlBody The XML response body from S3
     * @return array|null Array with parsed error info or null if parsing fails
     */
    public static function parseS3Error(string $xmlBody): ?array
    {
        if (empty($xmlBody)) {
            return null;
        }

        // Suppress XML parsing errors and handle them manually
        libxml_use_internal_errors(true);

        $xml = simplexml_load_string($xmlBody);

        // Clear libxml errors
        libxml_clear_errors();
        libxml_use_internal_errors(false);

        if (!$xml || !isset($xml->Code)) {
            return null;
        }

        return [
            'code' => (string)($xml->Code ?? ''),
            'message' => (string)($xml->Message ?? ''),
            'requestId' => (string)($xml->RequestId ?? ''),
            'hostId' => (string)($xml->HostId ?? ''),
        ];
    }

    /**
     * Build a clean error message from parsed S3 error
     *
     * @param array|null $errorData Parsed error data from parseS3Error()
     * @param int $statusCode HTTP status code
     * @return string Formatted error message
     */
    public static function buildErrorMessage(?array $errorData, int $statusCode): string
    {
        if ($errorData === null) {
            return "AWS S3 Error (HTTP {$statusCode})";
        }

        $code = $errorData['code'] ?? '';
        $message = $errorData['message'] ?? '';

        if (empty($code)) {
            return "AWS S3 Error (HTTP {$statusCode})";
        }

        if (empty($message)) {
            return "AWS S3 Error: {$code} (HTTP {$statusCode})";
        }

        return "AWS S3 Error: {$code} - {$message}";
    }
}
