<?php

namespace App\Data\Pagarme\Recipient;

use App\Data\Pagarme\PagarmeResponseData;
use App\Data\Pagarme\Recipient\Parts\Response\BankAccountData;

final readonly class RecipientResponseData extends PagarmeResponseData
{
    public function __construct(
        public ?string $id,
        public ?string $name,
        public ?string $email,
        public ?string $document,
        public ?string $type,
        public ?string $status,

        public ?BankAccountData $defaultBankAccount = null,

        public ?string $createdAt = null,
        public ?string $updatedAt = null,
    ) {}

    public function requireId(): string
    {
        if (! $this->id) {
            throw new \RuntimeException('Pagar.me recipient creation returned an empty id.');
        }

        return $this->id;
    }

    //

    public static function fromArray(array $payload): static
    {
        $bankAccount = static::arrArray($payload, 'default_bank_account');

        return new self(
            id:       static::arrString($payload, 'id'),
            name:     static::arrString($payload, 'name'),
            email:    static::arrString($payload, 'email'),
            document: static::arrString($payload, 'document'),
            type:     static::arrString($payload, 'type'),
            status:   static::arrString($payload, 'status'),

            defaultBankAccount: ! empty($bankAccount)
                ? BankAccountData::fromArray($bankAccount)
                : null,

            createdAt: static::arrString($payload, 'created_at'),
            updatedAt: static::arrString($payload, 'updated_at'),
        );
    }

    public function toArray(): array
    {
        return [
            'id'                   => $this->id,
            'name'                 => $this->name,
            'email'                => $this->email,
            'document'             => $this->document,
            'type'                 => $this->type,
            'status'               => $this->status,
            'default_bank_account' => $this->defaultBankAccount?->toArray(),
            'created_at'           => $this->createdAt,
            'updated_at'           => $this->updatedAt,
        ];
    }
}
