<?php

declare(strict_types=1);

class OAuthAccessTokenCookie extends ObjectModel
{
    public const TABLE = 'oauth_access_token_cookie';

    /**
     * @var int
     */
    public $id_oauth_access_token_cookie;

    /**
     * @var string
     */
    public $token;

    /**
     * @var string
     */
    public $name;

    /**
     * @var string|null
     */
    public $value;

    /**
     * @var int
     */
    public $expires;

    /**
     * @var array<string, mixed>
     *
     * @see ObjectModel::$definition
     */
    public static $definition
        = [
            'table' => self::TABLE,
            'primary' => 'id_oauth_access_token_cookie',
            'multilang' => false,
            'multilang_shop' => false,
            'fields' => [
                'token' => ['type' => self::TYPE_STRING, 'required' => true],
                'name' => ['type' => self::TYPE_STRING, 'required' => true],
                'value' => ['type' => self::TYPE_STRING, 'required' => false],
                'expires' => ['type' => self::TYPE_INT, 'required' => true],
            ],
        ];

    /**
     * @return OAuthAccessTokenCookie[]
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public static function getByToken(string $token): array
    {
        $db = Db::getInstance();

        $result = $db->executeS('SELECT * FROM `' . _DB_PREFIX_ . self::TABLE . '` WHERE `token` = "' . $db->escape($token) . '"');

        if (!is_array($result)) {
            $result = [];
        }

        return ObjectModel::hydrateCollection(
            self::class,
            $result
        );
    }

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public static function getByTokenAndName(string $token, string $name): ?OAuthAccessTokenCookie
    {
        $db = Db::getInstance();

        $result = $db->executeS('SELECT * FROM `' . _DB_PREFIX_ . self::TABLE . '` WHERE `token` = "' . $db->escape($token) . '" AND `name` = "' . $db->escape($name) . '"');

        if (!is_array($result)) {
            $result = [];
        }

        $ret = ObjectModel::hydrateCollection(
            self::class, $result
        );

        return count($ret) > 0 ? $ret[0] : null;
    }
}
