<?php

declare(strict_types=1);

namespace App\Infrastructure\Api\RapidMail\Commands;

use App\Infrastructure\Api\RapidMail\RecipientId;
use App\Infrastructure\Api\RapidMail\RecipientListId;

final readonly class UpdateRecipientCommand
{
    public function __construct(
        public RecipientId $id,
        public string $email,
        public ?string $firstname = null,
        public ?string $lastname = null,
        public ?string $title = null,
        public ?string $company = null,
        public ?string $zip = null,
        public ?string $city = null,
        public ?string $street = null,
        public ?string $country = null,
        public ?string $phone = null,
        public ?string $birthdate = null,
        public ?string $gender = null,
        public ?string $status = null,
        public ?RecipientListId $recipientListId = null,
        public array $customFields = []
    ) {
        if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Invalid email format');
        }
    }

    public function toArray(): array
    {
        $data = ['email' => $this->email];

        if ($this->firstname !== null) {
            $data['firstname'] = $this->firstname;
        }
        if ($this->lastname !== null) {
            $data['lastname'] = $this->lastname;
        }
        if ($this->title !== null) {
            $data['title'] = $this->title;
        }
        if ($this->company !== null) {
            $data['company'] = $this->company;
        }
        if ($this->zip !== null) {
            $data['zip'] = $this->zip;
        }
        if ($this->city !== null) {
            $data['city'] = $this->city;
        }
        if ($this->street !== null) {
            $data['street'] = $this->street;
        }
        if ($this->country !== null) {
            $data['country'] = $this->country;
        }
        if ($this->phone !== null) {
            $data['phone'] = $this->phone;
        }
        if ($this->birthdate !== null) {
            $data['birthdate'] = $this->birthdate;
        }
        if ($this->gender !== null) {
            $data['gender'] = $this->gender;
        }
        if ($this->status !== null) {
            $data['status'] = $this->status;
        }
        if ($this->recipientListId !== null) {
            $data['recipientlist_id'] = $this->recipientListId->value;
        }

        return array_merge($data, $this->customFields);
    }
}
