<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Mtc\MercuryDataModels\User;

class UserHasAccessToSite implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $user = User::query()->find($value);
        if (!$user) {
            $fail(__('validation.user_not_found'));
        }
        if (!$user->tenants()->where('tenants.id', tenant('id'))->exists()) {
            $fail(__('validation.invalid_user_selected'));
        }
    }
}
