<?php

namespace Openguru\OpenCartFramework\Cache;

use Openguru\OpenCartFramework\QueryBuilder\Connections\ConnectionInterface;

class DatabaseCache implements CacheInterface
{
    private $connection;
    private $table;

    public function __construct(ConnectionInterface $connection, string $table)
    {
        $this->connection = $connection;
        $this->table = $table;
    }

    public function get(string $key)
    {
        $cache = $this->connection->select(
            "
                SELECT result 
                FROM $this->table 
                WHERE cache_key = :key AND (expires_at IS NULL OR expires_at > NOW())
            ",
            [':key' => $key]
        );

        return $cache ? unserialize($cache[0]['result'], ['allowed_classes' => true]) : null;
    }

    public function set(string $key, $value, ?int $ttlSeconds = null): void
    {
        $this->connection->statement("DELETE FROM $this->table WHERE expires_at IS NOT NULL AND expires_at <= NOW()");

        $expiresAt = $ttlSeconds ? date('Y-m-d H:i:s', time() + $ttlSeconds) : null;

        $sql = <<<SQL
            INSERT INTO $this->table (cache_key, result, expires_at)
            VALUES (:key, :result, :expiresAt)
            ON DUPLICATE KEY UPDATE
                result = VALUES(result),
                expires_at = VALUES(expires_at)
        SQL;

        $this->connection->statement($sql, [
            ':key' => $key,
            ':result' => serialize($value),
            ':expiresAt' => $expiresAt,
        ]);
    }

    public function delete(string $key): void
    {
        $this->connection->statement("DELETE FROM $this->table WHERE cache_key = :key", [':key' => $key]);
    }

    public function clear(): void
    {
        $this->connection->truncateTable($this->table);
    }
}
