<?php

namespace Ignite\Core\Repositories;

use Ignite\Core\Auth\Authorization;
use Ignite\Core\Contracts\Repositories\PermissionRepository as PermissionRepositoryContract;
use Ignite\Core\Entities\GroupPermission;
use Ignite\Core\Entities\Permission;

class PermissionRepository implements PermissionRepositoryContract
{
    /**
     * @var Authorization
     */
    private $authorization;

    /**
     * PermissionRepository constructor.
     *
     * @param Authorization $authorization
     */
    public function __construct(Authorization $authorization)
    {
        $this->authorization = $authorization;
    }

    /**
     * The scoped Permission query.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        return Permission::query();
    }

    /**
     * Find a permission by primary key.
     *
     * @param  int $id
     *
     * @return \Ignite\Core\Entities\Permission
     */
    public function find($id)
    {
        return $this->query()->where('id', $id)->firstOrFail();
    }

    /**
     * Find a permission by key.
     *
     * @param  int $key
     * @return \Ignite\Core\Entities\Permission
     */
    public function findByKey($key)
    {
        return $this->query()->where('key', $key)->firstOrFail();
    }

    /**
     * Find all permissions in the system.
     *
     * @return \Ignite\Core\Collections\PermissionsCollection
     */
    public function findAll()
    {
        return Permission::all();
    }

    /**
     * Create a new permission.
     *
     * @param  array $data
     * @return Permission
     */
    public function create(array $data)
    {
        return Permission::create(array_merge([
            'is_user_defined' => 1
        ], $data));
    }

    /**
     * Update an existing permission.
     *
     * @param  int $id
     * @param  array $data
     *
     * @return \Ignite\Core\Entities\Permission
     */
    public function update($id, array $data)
    {
        $permission = $this->find($id);
        $permission->update($data);

        return $permission;
    }

    /**
     * Delete a permission.
     *
     * @param  int $id
     * @return \Ignite\Core\Entities\Permission
     * @throws \Exception
     */
    public function delete($id)
    {
        $permission = $this->find($id);
        $permission->delete();

        return $permission;
    }

    /**
     * Delete multiple permissions in one batch request.
     *
     * @param  array $ids
     * @return array
     */
    public function deleteMany(array $ids)
    {
        Permission::destroy($ids);

        return $ids;
    }

    /**
     * Flush the permission cache.
     *
     * @return \Ignite\Core\Auth\Authorization
     */
    public function flush()
    {
        return $this->authorization->forgetPermissions();
    }
}
