<?php

namespace Ignite\Core\Repositories;

use Ignite\Core\Contracts\Repositories\UserRepository as UserRepositoryContract;
use Ignite\Core\Entities\User;

class UserRepository implements UserRepositoryContract
{
    /**
     * The scoped User query.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        return User::with(['groups', 'groups.permissions']);
    }

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

    /**
     * Assign the provided groups to the given user.
     *
     * @param $id
     * @param array $groups
     *
     * @return \Ignite\Core\Entities\User
     */
    public function assignGroups($id, array $groups)
    {
        $user = $this->find($id);
        $user->groups()->sync($groups);
        $user->save();

        return $user;
    }

    /**
     * Activate a user.
     *
     * @param int $id
     * @return \Ignite\Core\Entities\User
     */
    public function activate($id)
    {
        $user = $this->find($id);
        $user->update(['status' => User::STAT_ACTIVE]);

        return $user;
    }

    /**
     * Deactivate a user.
     *
     * @param int $id
     * @return \Ignite\Core\Entities\User
     */
    public function deactivate($id)
    {
        $user = $this->find($id);
        $user->update(['status' => User::STAT_INACTIVE]);

        return $user;
    }

    /**
     * Find the admin user for the system.
     * (see core.admin config)
     *
     * @return User|null
     */
    public function findAdminUser(): ?User
    {
        /** @var ?User $user */ // Doing this instead of inlining this in order to appease my IDE :).
        $user = User::query()->firstWhere('email', config('core.admin.email'));

        return $user;
    }
}
