<?php

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

use App\Data\Pagarme\PagarmeData;

final readonly class PaymentData extends PagarmeData
{
    /**
     * @param  SplitData[]|null  $split
     */
    public function __construct(
        public string $paymentMethod,

        public ?array $split = null,

        public ?CreditCardData $creditCard = null,
        public ?PixData        $pix        = null,
    ) {
        self::requireIn($this->paymentMethod, ['credit_card', 'pix'], 'payments.payment_method');

        if ($this->paymentMethod === 'credit_card' && ! $this->creditCard) {
            throw new \InvalidArgumentException('payments.credit_card e obrigatorio para credit_card.');
        }

        if ($this->paymentMethod === 'pix' && ! $this->pix) {
            throw new \InvalidArgumentException('payments.pix e obrigatorio para pix.');
        }
    }

    /**
     * @param  SplitData[]|null  $split
     */
    public static function creditCard(CreditCardData $creditCard, ?array $split = null): self
    {
        return new self(
            paymentMethod: 'credit_card',
            creditCard:    $creditCard,
            split:         $split,
        );
    }

    /**
     * @param  SplitData[]|null  $split
     */
    public static function pix(PixData $pix, ?array $split = null): self
    {
        return new self(
            paymentMethod: 'pix',
            pix:           $pix,
            split:         $split,
        );
    }

    //

    public function toArray(): array
    {
        $payload = $this->filterFilledRecursive([
            'payment_method' => $this->paymentMethod,
            'split'          => $this->split,
        ]);

        if ($this->creditCard) {
            $payload['credit_card'] = $this->creditCard->toArray();
        }

        if ($this->pix) {
            $payload['pix'] = $this->pix->toArray();
        }

        return $payload;
    }
}
