<?php

namespace App\Data\Pagarme\Order\Parts\Response;

use App\Data\Pagarme\PagarmeResponseData;

final readonly class ChargeData extends PagarmeResponseData
{
    public function __construct(
        public ?string $id,
        public ?string $status,
        public ?int    $amount,
        public ?string $currency,
        public ?string $paidAt,
        public ?string $createdAt,
        public ?string $expiresAt = null,

        public ?TransactionData $lastTransaction,
    ) {}

    public function transaction(): ?TransactionData
    {
        return $this->lastTransaction;
    }

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

        return new self(
            id:        static::arrString($payload, 'id'),
            status:    static::arrString($payload, 'status'),
            amount:    static::arrInt($payload, 'amount'),
            currency:  static::arrString($payload, 'currency'),
            paidAt:    static::arrString($payload, 'paid_at'),
            createdAt: static::arrString($payload, 'created_at'),
            expiresAt: static::arrString($payload, 'expires_at'),

            lastTransaction: ! empty($transaction)
                ? TransactionData::fromArray($transaction)
                : null,
        );
    }

    public function toArray(): array
    {
        return array_filter([
            'id'               => $this->id,
            'status'           => $this->status,
            'amount'           => $this->amount,
            'currency'         => $this->currency,
            'paid_at'          => $this->paidAt,
            'created_at'       => $this->createdAt,
            'expires_at'       => $this->expiresAt,
            'last_transaction' => $this->lastTransaction?->toArray(),
        ], static fn ($v) => $v !== null);
    }
}
