<?php

namespace App\Data\Pagarme\Request\OrderRequestData\OrderPaymentData;

use App\Data\Pagarme\PagarmeData;

final readonly class OrderPaymentData extends PagarmeData
{
    /**
     * @param  OrderSplitData[]|null  $split
     */

    public function __construct(
        public string $paymentMethod,
        public ?OrderCreditCardData $creditCard = null, public ?OrderPixData $pix = null,
        public ?array $split = 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  OrderSplitData[]|null  $split
     */

    public static function creditCard(OrderCreditCardData $creditCard, ?array $split = null): self
    {
        return new self(
            paymentMethod: 'credit_card',
            creditCard:    $creditCard,
            split:         $split,
        );
    }

    /**
     * @param  OrderSplitData[]|null  $split
     */

    public static function pix(OrderPixData $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;
    }
}
