<?php

namespace App\Data\Pagarme;

abstract readonly class PagarmeResponseData
{
    abstract public static function fromArray(array $payload): static;

    abstract public function toArray(): array;

    //

    protected static function arrGet(array $payload, int|string $key, mixed $default = null): mixed
    {
        return array_key_exists($key, $payload) ? $payload[$key] : $default;
    }

    protected static function arrInt(array $payload, string $key): ?int
    {
        if (! array_key_exists($key, $payload)) {
            return null;
        }

        return (int) $payload[$key];
    }

    protected static function arrString(array $payload, string $key): ?string
    {
        if (! array_key_exists($key, $payload)) {
            return null;
        }

        $value = $payload[$key];

        return $value !== null && $value !== '' ? (string) $value : null;
    }

    protected static function arrBool(array $payload, string $key): ?bool
    {
        if (! array_key_exists($key, $payload)) {
            return null;
        }

        $value = $payload[$key];

        return $value !== null && $value !== '' ? (bool) $value : null;
    }

    protected static function arrArray(array $payload, string $key): array
    {
        if (! array_key_exists($key, $payload) || ! is_array($payload[$key])) {
            return [];
        }

        return $payload[$key];
    }

    protected static function arrMap(array $payload, string $key, callable $fn): array
    {
        return array_map($fn, static::arrArray($payload, $key));
    }
}
