<?php

namespace App\Http\Requests;

use App\Rules\SeoRedirectNotChained;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\SeoRedirect;

class StoreSeoRedirectRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $model = $this->route('redirect');
        $from_domain = $this->input('from_domain');

        return [
            'from_domain' => [
                'nullable',
                $this->domainValidationRule()
            ],
            'to_domain' => [
                'nullable',
                $this->domainValidationRule()
            ],
            'from' => [
                'required',
                $this->slugValidationRule(),
                new SeoRedirectNotChained($from_domain, $model?->id)
            ],
            'to' => [
                'required',
                $this->slugValidationRule()
            ],
            'code' => ['required', 'numeric'],
            'has_regex' => 'boolean',
        ];
    }

    /**
     * Validation rule for domain with protocol and no trailing slash.
     *
     * @return string
     */
    protected function domainValidationRule()
    {
        return 'regex:/^(https?:\/\/)([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}(\/.*)?$/i';
    }

    /**
     * Validation rule for slug format.
     *
     * @return string
     */
    protected function slugValidationRule()
    {
        // Extremely permissive: allows anything after the initial "/"
        // up to the end of the line (including multiple slashes, spaces,
        // punctuation, Unicode, etc.), but disallows newline characters.
        return 'regex:/^\/[^\r\n]*$/u';
    }


    /**
     * Add custom validation rules that run after the default Laravel validation rules.
     */
    protected function withValidator($validator)
    {
        $validator->after(function ($validator) {
            // Ensure 'from' and 'to' are not identical
            if ($this->input('from') === $this->input('to')) {
                $validator->errors()->add(
                    'to',
                    "The 'from' and 'to' fields must be different."
                );
            }
        });
    }
}
