<?php

namespace App\Http\Requests;

use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use App\Models\Role;
use App\Models\User;
use App\Support\UserActorAuthorization;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;

class UpdateRegisteredUserRequest extends FormRequest
{
    use PasswordValidationRules, ProfileValidationRules;

    public function authorize(): bool
    {
        $user = $this->route('user');

        return $user instanceof User && $this->actorMayManageUser($user);
    }

    /**
     * @return array<string, array<int, \Illuminate\Contracts\Validation\Rule|array<mixed>|string>>
     */
    public function rules(): array
    {
        /** @var User $user */
        $user = $this->route('user');

        return [
            'name' => $this->nameRules(),
            'email' => $this->emailRules($user->id),
            'password' => ['nullable', 'string', Password::default(), 'confirmed'],
            'role' => ['required', 'string', Rule::in($this->assignableRoleNames())],
            'avatar' => $this->avatarRules(),
        ];
    }

    /**
     * @return list<string>
     */
    protected function assignableRoleNames(): array
    {
        $query = Role::query()
            ->where('guard_name', 'web')
            ->where('is_active', true)
            ->orderBy('name', 'asc');

        $actor = $this->user();
        if (! ($actor instanceof User && $actor->hasRole('Master Admin', 'web'))) {
            $query->where('name', '!=', 'Master Admin');
        }

        return $query->pluck('name')->all();
    }

    private function actorMayManageUser(User $target): bool
    {
        $actor = $this->user();

        if (! $actor instanceof User) {
            return false;
        }

        return UserActorAuthorization::mayManage($actor, $target);
    }
}
