<?php

namespace App\Data\Pagarme;

abstract readonly class PagarmeData
{
    abstract public function toArray(): array;

    protected static function digits(?string $value): string
    {
        return preg_replace('/\D+/', '', (string) $value) ?? '';
    }

    protected function filterFilledRecursive(array $data): array
    {
        $filtered = [];

        foreach ($data as $key => $value) {
            if ($value instanceof self) {
                $value = $value->toArray();
            }

            if (is_array($value)) {
                $value = $this->filterFilledRecursive($value);
            }

            if ($value !== null && $value !== '' && $value !== []) {
                $filtered[$key] = $value;
            }
        }

        return $filtered;
    }

    protected static function requireFilled(mixed $value, string $field): void
    {
        if ($value === null || $value === '' || $value === []) {
            throw new \InvalidArgumentException("{$field} e obrigatorio.");
        }
    }

    protected static function requireIn(string $value, array $allowed, string $field): void
    {
        if (! in_array($value, $allowed, true)) {
            throw new \InvalidArgumentException("{$field} invalido.");
        }
    }

    protected static function requirePositiveInt(int $value, string $field): void
    {
        if ($value <= 0) {
            throw new \InvalidArgumentException("{$field} deve ser maior que zero.");
        }
    }
}
