<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Auth;

class MtcRoleRestriction implements Rule
{
    private string $failureMessage = '';

    /**
     * @param string $email The email address of the user being assigned the role
     */
    public function __construct(private string $email)
    {
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if (strtolower($value) !== 'mtc') {
            return true;
        }

        if (!Auth::user()->hasRole('mtc')) {
            $this->failureMessage = 'Only MTC users can assign the MTC role.';
            return false;
        }

        $allowedDomains = config('auth.mtc_allowed_email_domains', ['@mtc.co.uk']);
        $emailLower = strtolower($this->email);

        if (!collect($allowedDomains)->contains(fn ($domain) => str_contains($emailLower, strtolower($domain)))) {
            $this->failureMessage = 'The MTC role can only be assigned to users with an approved email address.';
            return false;
        }

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->failureMessage;
    }
}
