<?php
/**
 * Copyright 2022 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Magento\Mray\Index\Persistence;

use Magento\Mray\Index\Collection\DbSchema;
use function clearstatcache;
use function is_dir;
use function mkdir;
use function realpath;

class DbSchemaStorage
{
    private const PATH = '/dbSchema';

    /**
     * @var string
     */
    private $dir;

    /**
     * @param string $dataDir
     */
    public function __construct(string $dataDir)
    {
        $dir = $dataDir . self::PATH;
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
            clearstatcache(true, $dir);
        }

        $this->dir = realpath($dir);
    }

    /**
     * @param DbSchema $dbSchema
     * @param string $version
     */
    public function saveVersion(DbSchema $dbSchema, string $version)
    {
        (new FileWriter())->write(sprintf('%s/%s.php', $this->dir, $version), $dbSchema->exportData());
    }
}
