<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Model;

use WriteTextAI\WriteTextAI\Model\UserWebTokenFactory;
use WriteTextAI\WriteTextAI\Api\UserWebTokenRepositoryInterface;
use Magento\Framework\App\CacheInterface;

class UserWebTokenManager
{
    /**
     * @var UserWebTokenFactory
     */
    protected $userWebTokenFactory;

    /**
     * @var UserWebTokenRepositoryInterface
     */
    protected $userWebTokenRepository;

    /**
     * @var CacheInterface
     */
    protected $cache;

    /**
     * Cache key prefix for user web tokens
     */
    protected const CACHE_KEY_PREFIX = 'wtai_user_web_token_';

    /**
     * Cache lifetime in seconds (59 minutes)
     */
    protected const CACHE_LIFETIME = 3540;

    /**
     * Constructor
     *
     * @param UserWebTokenFactory $userWebTokenFactory
     * @param UserWebTokenRepositoryInterface $userWebTokenRepository
     * @param CacheInterface $cache
     */
    public function __construct(
        UserWebTokenFactory $userWebTokenFactory,
        UserWebTokenRepositoryInterface $userWebTokenRepository,
        CacheInterface $cache
    ) {
        $this->userWebTokenFactory = $userWebTokenFactory;
        $this->userWebTokenRepository = $userWebTokenRepository;
        $this->cache = $cache;
    }

    /**
     * Get user web token
     *
     * @param int $userId
     * @return string
     */
    public function getUserWebToken($userId)
    {
        // Check cache first
        $cacheKey = self::CACHE_KEY_PREFIX . $userId;
        $cachedToken = $this->cache->load($cacheKey);
        
        if ($cachedToken !== false) {
            return $cachedToken;
        }

        // If not in cache, get from database
        $userWebToken = $this->userWebTokenFactory->create();
        $userWebToken = $userWebToken->getCollection()
            ->addFieldToFilter('user_id', $userId)
            ->getFirstItem();

        if ($userWebToken->getId()) {
            $token = $userWebToken->getToken();
            // Save to cache with 59-minute expiration
            $this->cache->save($token, $cacheKey, [], self::CACHE_LIFETIME);
            return $token;
        } else {
            return '';
        }
    }

    /**
     * Get token email
     *
     * @param int $userId
     * @return string
     */
    public function getTokenEmail($userId)
    {
        $userWebToken = $this->userWebTokenFactory->create();
        $userWebToken = $userWebToken->getCollection()
            ->addFieldToFilter('user_id', $userId)
            ->getFirstItem();

        if ($userWebToken->getId()) {
            return $userWebToken->getEmail();
        } else {
            return '';
        }
    }

    /**
     * Set user web token
     *
     * @param int $userId
     * @param string $token
     * @param string $email
     * @return void
     */
    public function setUserWebToken($userId, $token, $email = '')
    {
        $userWebToken = $this->userWebTokenFactory->create();

        $existing = $userWebToken->getCollection()
            ->addFieldToFilter('user_id', $userId)
            ->getFirstItem();

        if ($existing->getId()) {
            // Update the existing record
            $existing->setToken($token);
            $existing->setEmail($email);
            $userWebToken = $existing;
        } else {
            // Record not found, create a new one
            $userWebToken->setData([
                "user_id" => $userId,
                "token" => $token,
                "email" => $email
            ]);
        }

        $this->userWebTokenRepository->save($userWebToken);
        
        // Save to cache with 59-minute expiration
        $cacheKey = self::CACHE_KEY_PREFIX . $userId;
        $this->cache->save($token, $cacheKey, ['wtai_user_web_token'], self::CACHE_LIFETIME);
    }

    /**
     * Get only the first user web token
     */
    public function getFirstUserWebToken()
    {
        $userWebToken = $this->userWebTokenFactory->create();
        $userWebToken = $userWebToken->getCollection()
            ->getFirstItem();

        if ($userWebToken->getId()) {
            return $userWebToken->getToken();
        } else {
            return '';
        }
    }

    /**
     * Delete user web token
     *
     * @param int $userId
     * @return void
     */
    public function deleteUserWebToken($userId)
    {
        $userWebToken = $this->userWebTokenFactory->create();

        $existing = $userWebToken->getCollection()
            ->addFieldToFilter('user_id', $userId)
            ->getFirstItem();
            
        // Remove from cache
        $cacheKey = self::CACHE_KEY_PREFIX . $userId;
        $this->cache->remove($cacheKey);

        if ($existing->getId()) {
            $this->userWebTokenRepository->delete($existing);
        }
    }

    /**
     * Delete all user web token
     *
     * @return void
     */
    public function deleteAllUserWebToken()
    {
        $userWebToken = $this->userWebTokenFactory->create();
        
        // Get all user IDs before deletion for cache cleanup
        $collection = $userWebToken->getCollection();
        $userIds = [];
        foreach ($collection as $token) {
            $userIds[] = $token->getUserId();
        }
        
        // Delete all tokens from database
        $collection->walk('delete');
        
        // Remove all cached tokens
        foreach ($userIds as $userId) {
            $cacheKey = self::CACHE_KEY_PREFIX . $userId;
            $this->cache->remove($cacheKey);
        }
    }
}
