<?php

namespace App\Data\Pagarme\Response\OrderResponseData\OrderChargeResponseData;

use App\Data\Pagarme\PagarmeResponseData;

final readonly class OrderChargeResponseData extends PagarmeResponseData
{
    public function __construct(
        public ?string $id,
        public ?string $status,
        public ?int    $amount,
        public ?string $currency,
        public ?string $paidAt,
        public ?string $createdAt,
        public ?OrderTransactionResponseData $lastTransaction,
    ) {}

    public function transaction(): ?OrderTransactionResponseData
    {
        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'),

            lastTransaction: ! empty($transaction)
                ? OrderTransactionResponseData::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,
            'last_transaction' => $this->lastTransaction?->toArray(),
        ], static fn ($v) => $v !== null);
    }
}
