<?php

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

use App\Data\Pagarme\PagarmeData;
use App\Models\Address;

final readonly class BillingAddressData extends PagarmeData
{
    public function __construct(
        public string  $line1,
        public ?string $line2,
        public string  $zipCode,
        public string  $city,
        public string  $state,
        public string  $country,
    ) {
        self::requireFilled($this->line1, 'billing_address.line_1');
        self::requireFilled($this->zipCode, 'billing_address.zip_code');
        self::requireFilled($this->city, 'billing_address.city');
        self::requireFilled($this->state, 'billing_address.state');
        self::requireFilled($this->country, 'billing_address.country');
    }

    public static function fromAddress(?Address $address): self
    {
        $state = $address?->state?->code ?? $address?->city?->state?->code;
        $city  = $address?->city?->name;

        $line1 = implode(', ', array_filter([
            $address?->number ?: 'S/N',
            $address?->address,
            $address?->district,
        ]));

        return new self(
            line1:   $line1,
            line2:   $address?->complement ?: $address?->instructions,
            zipCode: self::digits($address?->zip_code),
            city:    (string) $city,
            state:   (string) $state,
            country: 'BR',
        );
    }

    //

    public function toArray(): array
    {
        return $this->filterFilledRecursive([
            'line_1'   => $this->line1,
            'line_2'   => $this->line2,
            'zip_code' => $this->zipCode,
            'city'     => $this->city,
            'state'    => $this->state,
            'country'  => $this->country,
        ]);
    }
}
