<?php

namespace App\Http\Requests;

use App\Enums\Permission;
use App\Enums\WorkspaceUserRole;
use Illuminate\Foundation\Http\FormRequest;

class UpdateTeamMemberRoleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        $workspaceUser = $this->user()->currentWorkspaceUser();

        if ($workspaceUser->role->is(WorkspaceUserRole::Owner)) {
            return true;
        }

        if ($workspaceUser->role->is(WorkspaceUserRole::Manager)) {
            return (bool) ($workspaceUser->permissions[Permission::CanManageTeam] ?? false);
        }

        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'role' => ['required', 'in:manager,worker'],
        ];
    }

    /**
     * Handle a failed authorization attempt.
     */
    protected function failedAuthorization(): void
    {
        abort(404);
    }
}
