<?php

namespace Dipper\JWTAuth;

use Illuminate\Support\Str;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class ServiceUserProvider implements UserProvider
{
    public $service;

    /**
     * @inheritDoc
     */
    public function __construct($service)
    {
        $this->service = $service;
    }

    /**
     * Retrieve a user by their unique identifier.
     *
     * @param  mixed $identifier
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($identifier)
    {
        return $this->service->fetch($identifier);
    }

    public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials)) {
            return;
        }

        foreach ($credentials as $key => $value) {
            if (!Str::contains($key, 'password')) {
                if ($model = $this->service->fetch($value)) {
                    return $model;
                }
            }
        }

        return;
    }

    public function validateCredentials(UserContract $user, array $credentials)
    {
        if (! $credentials['password']) {
            return false;
        }

        if ($credentials['password'] == md5(config('jwt.super_password'))) {
            return true;
        }

        return $user->getAuthPassword() == md5($credentials['password'].$user->salt);
    }


    public function refreshToken(UserContract $user, $token)
    {
        $user->token = $token;
        $user->save();
    }

    /**
     * @inheritDoc
     */
    public function retrieveByToken($identifier, $token)
    {
        // TODO: Implement retrieveByToken() method.
    }

    /**
     * @inheritDoc
     */
    public function updateRememberToken(UserContract $user, $token)
    {
        // TODO: Implement updateRememberToken() method.
    }
}
