<?php

namespace PortalPeople\virtualstock\services;

use Yii;
use yii\base\BaseObject;
use yii\helpers\FileHelper;

class VirtualStockCursorStore extends BaseObject
{
    public string $cacheKey = 'virtualstock.order-import.cursor';
    public string $filePath = '@runtime/virtualstock/order-import.cursor';

    public function get(): ?string
    {
        $cached = $this->readFromCache();
        if ($cached !== null) {
            return $cached;
        }

        $fileValue = $this->readFromFile();
        if ($fileValue !== null) {
            $this->writeToCache($fileValue);
        }

        return $fileValue;
    }

    public function set(?string $cursor): void
    {
        if ($cursor === null || $cursor === '') {
            return;
        }

        $this->writeToCache($cursor);
        $this->writeToFile($cursor);
    }

    public function clear(): void
    {
        if (Yii::$app->has('cache')) {
            Yii::$app->cache->delete($this->cacheKey);
        }

        $path = $this->resolvePath();
        if (is_file($path)) {
            @unlink($path);
        }
    }

    private function readFromCache(): ?string
    {
        if (!Yii::$app->has('cache')) {
            return null;
        }

        $value = Yii::$app->cache->get($this->cacheKey);
        if (!is_string($value) || $value === '') {
            return null;
        }

        return $value;
    }

    private function writeToCache(string $cursor): void
    {
        if (!Yii::$app->has('cache')) {
            return;
        }

        Yii::$app->cache->set($this->cacheKey, $cursor);
    }

    private function readFromFile(): ?string
    {
        $path = $this->resolvePath();
        if (!is_file($path)) {
            return null;
        }

        $value = trim((string) @file_get_contents($path));
        if ($value === '') {
            return null;
        }

        return $value;
    }

    private function writeToFile(string $cursor): void
    {
        $path = $this->resolvePath();
        $dir = dirname($path);
        FileHelper::createDirectory($dir);
        file_put_contents($path, $cursor, LOCK_EX);
    }

    private function resolvePath(): string
    {
        return Yii::getAlias($this->filePath);
    }
}
