<?php

namespace App\Data\Pagarme\Card;

use App\Data\Pagarme\PagarmeResponseData;

final readonly class CardResponseData extends PagarmeResponseData
{
    public function __construct(
        public ?string $id,
        public ?string $firstSixDigits,
        public ?string $lastFourDigits,
        public ?string $brand,
        public ?string $holderName,
        public ?int    $expMonth,
        public ?int    $expYear,
        public ?string $status,
        public ?string $type,
        public ?string $createdAt = null,
        public ?string $updatedAt = null,
    ) {}

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

        return $this->id;
    }

    //

    public static function fromArray(array $payload): static
    {
        return new self(
            id:             static::arrString($payload, 'id'),
            firstSixDigits: static::arrString($payload, 'first_six_digits'),
            lastFourDigits: static::arrString($payload, 'last_four_digits'),
            brand:          static::arrString($payload, 'brand'),
            holderName:     static::arrString($payload, 'holder_name'),
            expMonth:       static::arrInt($payload, 'exp_month'),
            expYear:        static::arrInt($payload, 'exp_year'),
            status:         static::arrString($payload, 'status'),
            type:           static::arrString($payload, 'type'),
            createdAt:      static::arrString($payload, 'created_at'),
            updatedAt:      static::arrString($payload, 'updated_at'),
        );
    }

    public function toArray(): array
    {
        return [
            'id'               => $this->id,
            'first_six_digits' => $this->firstSixDigits,
            'last_four_digits' => $this->lastFourDigits,
            'brand'            => $this->brand,
            'holder_name'      => $this->holderName,
            'exp_month'        => $this->expMonth,
            'exp_year'         => $this->expYear,
            'status'           => $this->status,
            'type'             => $this->type,
            'created_at'       => $this->createdAt,
            'updated_at'       => $this->updatedAt,
        ];
    }
}
