<?php

namespace App\Actions;

use App\Enums\RoleSlug;
use App\Models\Role;
use App\Models\User;

class UpdateUserAction
{
    /**
     * @param  array{name?: string, email?: string, password?: string, role?: RoleSlug}  $data
     */
    public function handle(User $user, array $data): User
    {
        if (isset($data['role'])) {
            abort_if(
                $user->isAdmin() && $data['role'] !== RoleSlug::Admin && $this->isLastAdmin($user),
                403,
                'The last admin cannot be demoted.',
            );

            $data['role_id'] = Role::query()->where('slug', $data['role'])->firstOrFail()->id;
            unset($data['role']);
        }

        $user->update($data);

        return $user->refresh();
    }

    protected function isLastAdmin(User $user): bool
    {
        return ! User::query()
            ->whereKeyNot($user->id)
            ->whereRelation('role', 'slug', RoleSlug::Admin)
            ->exists();
    }
}
