<?php

namespace App\Domains\Bootstrap\Requests;

use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Closure;
use Illuminate\Foundation\Http\FormRequest;

class TenantBootstrapRequest extends FormRequest
{
    protected bool $hasInvalidDomain = false;

    protected bool $hasInvalidPath = false;

    public function authorize(): bool
    {
        return true;
    }

    protected function prepareForValidation(): void
    {
        $rawDomain = $this->query('dominio', $this->route('dominio'));
        $rawPath = $this->query('path', '/');
        $normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
        $normalizedPath = TenantDomainNormalizer::normalizePath($rawPath);

        $this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
            && $normalizedDomain === null;

        $this->hasInvalidPath = ! is_string($rawPath) || $normalizedPath === null;

        $this->merge([
            'dominio' => $normalizedDomain,
            'path' => $normalizedPath,
        ]);
    }

    /** @return array<string, mixed> */
    public function rules(): array
    {
        return [
            'dominio' => [
                'bail',
                function (string $attribute, mixed $value, Closure $fail): void {
                    if ($this->hasInvalidDomain) {
                        $fail("The {$attribute} field must contain a valid domain or URL.");
                    }
                },
                'required',
                'string',
                'max:255',
            ],
            'path' => [
                'bail',
                function (string $attribute, mixed $value, Closure $fail): void {
                    if ($this->hasInvalidPath) {
                        $fail("The {$attribute} field must contain a valid URL path.");
                    }
                },
                'required',
                'string',
                'max:2048',
            ],
        ];
    }
}
