<?php

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

use App\Data\Pagarme\PagarmeResponseData;

final readonly class TransactionData extends PagarmeResponseData
{
    public function __construct(
        public ?string $id,
        public ?string $status,
        public ?int    $amount,
        public ?int    $cost,
        public ?string $createdAt,
        public ?string $acquirerMessage,
        public array   $gatewayResponse,
        public ?string $qrCode        = null,
        public ?string $qrCodeUrl     = null,
        public ?string $expiresAt     = null,
    ) {}

    public static function fromArray(array $payload): static
    {
        return new self(
            id:              static::arrString($payload, 'id'),
            status:          static::arrString($payload, 'status'),
            amount:          static::arrInt($payload, 'amount'),
            cost:            static::arrInt($payload, 'cost'),
            createdAt:       static::arrString($payload, 'created_at'),
            acquirerMessage: static::arrString($payload, 'acquirer_message'),
            gatewayResponse: static::arrArray($payload, 'gateway_response'),
            qrCode:          static::arrString($payload, 'qr_code'),
            qrCodeUrl:       static::arrString($payload, 'qr_code_url'),
            expiresAt:       static::arrString($payload, 'expires_at'),
        );
    }

    public function toArray(): array
    {
        return array_filter([
            'id'               => $this->id,
            'status'           => $this->status,
            'amount'           => $this->amount,
            'cost'             => $this->cost,
            'created_at'       => $this->createdAt,
            'acquirer_message' => $this->acquirerMessage,
            'gateway_response' => $this->gatewayResponse,
            'qr_code'          => $this->qrCode,
            'qr_code_url'      => $this->qrCodeUrl,
            'expires_at'       => $this->expiresAt,
        ], static fn ($v) => $v !== null);
    }
}
