<?php

declare(strict_types=1);

namespace CloudXM\NFe\DTOs;

/**
 * Tenant Config Resource DTO
 * 
 * Represents the v2 API response for tenant configuration
 */
class TenantConfigResource
{
    public function __construct(
        public string $tenant_id,
        public NfseConfig $nfse,
        public ApiConfig $api
    ) {}

    /**
     * Create from API response array
     * 
     * @throws \InvalidArgumentException if required fields are missing
     */
    public static function fromArray(array $data): self
    {
        if (!isset($data['tenant_id'])) {
            throw new \InvalidArgumentException('Missing required field: tenant_id');
        }

        if (!isset($data['nfse']) || !is_array($data['nfse'])) {
            throw new \InvalidArgumentException('Missing required field: nfse');
        }

        if (!isset($data['api']) || !is_array($data['api'])) {
            throw new \InvalidArgumentException('Missing required field: api');
        }

        return new self(
            tenant_id: $data['tenant_id'],
            nfse: NfseConfig::fromArray($data['nfse']),
            api: ApiConfig::fromArray($data['api'])
        );
    }

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

        if (empty($this->tenant_id)) {
            $errors['tenant_id'] = 'Tenant ID is required';
        }

        $nfseErrors = $this->nfse->validate();
        if (!empty($nfseErrors)) {
            $errors['nfse'] = $nfseErrors;
        }

        return $errors;
    }
}
