<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class UniqueGroupName implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $typeId = request()->input('group_type');

        // Check if a group with the same name and app_id exists
        $exists = \App\Models\Group::where('app_id', \Auth::user()->app_id)
            ->where('type_id', $typeId) // Fetch type_id from request
            ->where('name', $value)
            ->exists();

        // If the record exists, trigger the failure callback
        if ($exists) {
            $fail(__('validation.unique'));
        }
    }
}
