<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonPickwareCommon\Classes;

use Shopware\Components\Model\ModelManager;
use Shopware\Models\User\User;
use Zend_Auth_Adapter_Http_Resolver_Interface as AuthResolverInterface;

/**
 * @see https://github.com/shopware/shopware/commit/a4139e5bd6e51d7c3787e98db3eacb1ddd838fdc
 */
class BasicAuthResolver implements AuthResolverInterface
{
    /**
     * @var ModelManager
     */
    protected $entityManager;

    /**
     * @param ModelManager $entityManager
     */
    public function __construct(ModelManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * @inheritdoc
     */
    public function resolve($username, $realm)
    {
        $user = $this->entityManager->getRepository(User::class)->findOneBy([
            'username' => $username,
            'active' => true,
        ]);
        if (!$user) {
            return false;
        }

        $apiKey = $user->getApiKey();
        if (empty($apiKey)) {
            return false;
        }

        return $apiKey;
    }
}
