<?php

declare(strict_types=1);

namespace CloudXM\NFe\DTOs;

use JsonSerializable;

/**
 * Address Data DTO
 * 
 * Represents address information for invoice client
 */
class AddressData implements JsonSerializable
{
    public function __construct(
        public ?string $street = null,
        public ?string $number = null,
        public ?string $district = null,
        public ?string $city = null,
        public ?string $state = null,
        public ?string $zipcode = null
    ) {
        if ($this->zipcode !== null) {
            $this->zipcode = preg_replace('/[^0-9]/', '', $this->zipcode);
        }
    }

    /**
     * Validate address data
     * 
     * @return array Empty array if valid, array of errors if invalid
     */
    public function validate(): array
    {
        $errors = [];

        // All fields are optional for address
        // But if provided, validate format
        if ($this->state !== null && strlen($this->state) !== 2) {
            $errors['state'] = 'State must be 2 characters';
        }

        if ($this->zipcode !== null && !preg_match('/^\d{8}$/', $this->zipcode)) {
            $errors['zipcode'] = 'Invalid zipcode format';
        }

        return $errors;
    }

    /**
     * Serialize to JSON for API request
     */
    public function jsonSerialize(): array
    {
        return array_filter([
            'street' => $this->street,
            'number' => $this->number,
            'district' => $this->district,
            'city' => $this->city,
            'state' => $this->state,
            'zipcode' => $this->zipcode,
        ], fn($value) => $value !== null);
    }
}
