<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Mtc\MercuryDataModels\SeoRedirect;

class SeoRedirectNotChained implements Rule
{
    protected $fromDomain;
    protected $excludeId;

    public function __construct(string $fromDomain = null, int $excludeId = null)
    {
        $this->fromDomain = $fromDomain;
        $this->excludeId = $excludeId;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return SeoRedirect::query()
            ->when($this->excludeId, fn($query) => $query->where('id', '!=', $this->excludeId))
            ->where($attribute, $value)
            ->where('from_domain', $this->fromDomain)
            ->doesntExist();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The combination of from and from_domain already has a redirect set up, creating a chain.';
    }
}
