<?php


namespace App\Services\Core\Auth;

use App\Exceptions\GeneralException;
use App\Helpers\Core\Traits\HasWhen;
use App\Hooks\User\BeforeRoleCreated;
use App\Hooks\User\BeforeRoleUpdated;
use App\Hooks\User\WhileRoleDeleting;
use App\Models\Core\Auth\Role;
use App\Notifications\Core\Role\RoleNotification;
use App\Services\Core\BaseService;

class RoleService extends BaseService
{
    use HasWhen;
    /**
     * @param Role $role
     */
    public function __construct(Role $role)
    {
        $this->model = $role;
    }


    public function update(): Role
    {
        throw_if(
            $this->model->isAdmin(),
            new GeneralException(__t('action_not_allowed'))
        );

        $this->model->fill($this->getFillAble(request()->except('is_default', 'is_admin')));

        $condition = $this->model->isDirty() || ($this->model->permissions()->count() !== count(request()->get('permissions', [])));

        $this->when($condition, function (RoleService $service) {
            $service->notify('roles_updated');
        })->when(count(request()->get('permissions', [])), function (RoleService $service) {
            $service->syncPermissions(request()->get('permissions'));
        });

        $this->model->save();

        return $this->model;
    }

    public function delete(): static
    {
        if ($this->model->isDefault())
            throw new GeneralException(trans('default.default_delete', ['name' => 'role']));

        $this->model->delete();

        return $this;
    }


    public function assignPermissions(array $permissions, $attach = false): array|static
    {
        if (!$attach)
            return $this->model->permissions()->sync($permissions);

        foreach ($permissions as $permission) {
            $this->model->permissions()->attach($permission['permission_id'], [
                'meta' => json_encode(isset($permission['meta']) ? $permission['meta'] : [])
            ]);
        }

        return $this;
    }


    public function syncPermissions(array $permissions): array|static
    {
        $this->model->permissions()->sync([]);
        return $this->assignPermissions($permissions);
    }


    public function attachPermissions(Role $role): Role
    {
        if ($role->isDefault())
            throw new GeneralException(trans('default.default_update', ['name' => 'role']));

        $permissions = is_array(request('permissions')) ? request('permissions') : [request('permissions')];
        foreach ($permissions as $key => $permission) {
            if (!$role->permissions->contains($permission)) {
                $role
                    ->permissions()
                    ->attach($permission);
            }
        }

        return $role->load('permissions');
    }

    public function detachPermissions(Role $role): Role
    {
        $permissions = is_array(request('permissions')) ? request('permissions') : [request('permissions')];

        $role
            ->permissions()
            ->detach($permissions);

        return $role->load("permissions");
    }

    public function beforeCreated(): static
    {
        BeforeRoleCreated::new()
            ->handle();

        return $this;
    }

    public function beforeUpdated(): static
    {
        BeforeRoleUpdated::new()
            ->setModel($this->model)
            ->handle();

        return $this;
    }

    public function whileDeleting(): static
    {
        WhileRoleDeleting::new()
            ->setModel($this->model)
            ->handle();

        return $this;
    }

    public function notify(string $event, $role = null): static
    {
        notify()
            ->on($event)
            ->with($role ?: $this->model)
            ->send(RoleNotification::class);

        return $this;
    }



}
