<?php

namespace App\Data\Pagarme\Customer;

use App\Data\Pagarme\Customer\Parts\Response\AddressData;
use App\Data\Pagarme\Customer\Parts\Response\PhonesData;
use App\Data\Pagarme\PagarmeResponseData;

final readonly class CustomerResponseData extends PagarmeResponseData
{
    public function __construct(
        public ?string $id,
        public ?string $name,
        public ?string $email,
        public ?string $code,
        public ?string $document,
        public ?string $documentType,
        public ?string $type,
        public ?bool   $delinquent,

        public ?AddressData $address, public PhonesData $phones,

        public ?string $createdAt = null,
        public ?string $updatedAt = null,
    ) {}

    public function requireId(): string
    {
        if (! $this->id) {
            throw new \RuntimeException('Customer creation returned an empty id.');
        }

        return $this->id;
    }

    //

    public static function fromArray(array $payload): static
    {
        $address = static::arrArray($payload, 'address');
        $phones  = static::arrArray($payload, 'phones');

        return new self(
            id:           static::arrString($payload, 'id'),
            name:         static::arrString($payload, 'name'),
            email:        static::arrString($payload, 'email'),
            code:         static::arrString($payload, 'code'),
            document:     static::arrString($payload, 'document'),
            documentType: static::arrString($payload, 'document_type'),
            type:         static::arrString($payload, 'type'),
            delinquent:   static::arrBool($payload, 'delinquent'),

            address: ! empty($address) ? AddressData::fromArray($address) : null,

            phones:    PhonesData::fromArray($phones),
            createdAt: static::arrString($payload, 'created_at'),
            updatedAt: static::arrString($payload, 'updated_at'),
        );
    }

    public function toArray(): array
    {
        return [
            'id'            => $this->id,
            'name'          => $this->name,
            'email'         => $this->email,
            'code'          => $this->code,
            'document'      => $this->document,
            'document_type' => $this->documentType,
            'type'          => $this->type,
            'delinquent'    => $this->delinquent,
            'address'       => $this->address?->toArray(),
            'phones'        => $this->phones->toArray(),
            'created_at'    => $this->createdAt,
            'updated_at'    => $this->updatedAt,
        ];
    }
}
