<?php

declare(strict_types=1);

namespace CloudXM\NFe\DTOs;

/**
 * NFSe Config DTO
 * 
 * Represents NFSe configuration in tenant config response
 */
class NfseConfig
{
    public function __construct(
        public string $default_environment,
        public string $tax_regime,
        public ?string $national_service_code = null,
        public ?string $municipal_service_code = null,
        public ?string $nbs_code = null,
        public ?string $tax_classification = null,
        public string $dps_series = '1',
        public ?string $municipal_registration = null,
        public ?string $trade_name = null,
        public ?string $municipality_code = null,
        public ?int $next_homologation_number = null,
        public ?int $next_production_number = null,
        public int $grace_period = 0,
        public bool $iss_rate_required = false,
        public ?string $complementary_information = null
    ) {}

    /**
     * Create from API response array
     */
    public static function fromArray(array $data): self
    {
        return new self(
            default_environment: $data['default_environment'] ?? 'homologation',
            tax_regime: $data['tax_regime'] ?? 'simple',
            national_service_code: $data['national_service_code'] ?? null,
            municipal_service_code: $data['municipal_service_code'] ?? null,
            nbs_code: $data['nbs_code'] ?? null,
            tax_classification: $data['tax_classification'] ?? null,
            dps_series: $data['dps_series'] ?? '1',
            municipal_registration: $data['municipal_registration'] ?? null,
            trade_name: $data['trade_name'] ?? null,
            municipality_code: $data['municipality_code'] ?? null,
            next_homologation_number: $data['next_homologation_number'] ?? null,
            next_production_number: $data['next_production_number'] ?? null,
            grace_period: $data['grace_period'] ?? 0,
            iss_rate_required: $data['iss_rate_required'] ?? false,
            complementary_information: $data['complementary_information'] ?? null
        );
    }

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

        $validEnvironments = ['homologation', 'production'];
        if (!in_array($this->default_environment, $validEnvironments, true)) {
            $errors['default_environment'] = 'Invalid environment value';
        }

        if ($this->grace_period < 0) {
            $errors['grace_period'] = 'Grace period must be non-negative';
        }

        return $errors;
    }
}
