<?php

namespace App\Exceptions;

use Illuminate\Http\Client\Response;
use RuntimeException;

class MetaMarketingApiException extends RuntimeException
{
    public function __construct(
        string $operation,
        public readonly int $httpStatus,
        public readonly array $metaError,
        public readonly array $responseBody = []
    ) {
        $message = trim((string) data_get($metaError, 'message', 'Unknown Meta API error'));
        $code = data_get($metaError, 'code');
        $subcode = data_get($metaError, 'error_subcode');
        $traceId = data_get($metaError, 'fbtrace_id');
        $details = array_filter([
            "HTTP {$httpStatus}",
            $code !== null ? "code {$code}" : null,
            $subcode !== null ? "subcode {$subcode}" : null,
            $traceId ? "trace {$traceId}" : null,
        ]);

        parent::__construct(sprintf('%s failed (%s): %s', $operation, implode(', ', $details), $message));
    }

    public static function fromResponse(string $operation, Response $response): self
    {
        $body = $response->json();
        $body = is_array($body) ? $body : ['raw_body' => $response->body()];
        $error = data_get($body, 'error');
        $error = is_array($error) ? $error : ['message' => $response->body() ?: 'Unknown Meta API error'];

        return new self($operation, $response->status(), $error, $body);
    }

    public function logContext(): array
    {
        return [
            'http_status' => $this->httpStatus,
            'message' => (string) data_get($this->metaError, 'message', $this->getMessage()),
            'type' => data_get($this->metaError, 'type'),
            'code' => data_get($this->metaError, 'code'),
            'subcode' => data_get($this->metaError, 'error_subcode'),
            'user_title' => data_get($this->metaError, 'error_user_title'),
            'user_message' => data_get($this->metaError, 'error_user_msg'),
            'trace_id' => data_get($this->metaError, 'fbtrace_id'),
            'response' => $this->responseBody,
        ];
    }
}
