import dotenv from 'dotenv';
import path from 'path';
import { StorageInterface } from "./StorageInterface";
import JsonStorage from "./json";
import RedisStorage from "./redis";
import MemoryStorage from "./memory";

const ENVIRONMENT = process.env.NODE_ENV ?? 'production';
dotenv.config({ path: path.resolve(__dirname, `../../.env.${ENVIRONMENT}`) });

const JSON_KEY = 'json';
const REDIS_KEY = 'redis';
const MEMORY_KEY = 'memory';

let storage: StorageInterface;
if (!process.env.STORAGE || process.env.STORAGE?.toLowerCase() === JSON_KEY) {
    storage = new JsonStorage();
} else if (process.env.STORAGE?.toLowerCase() === REDIS_KEY) {
    storage = new RedisStorage();
} else if (process.env.STORAGE?.toLowerCase() === MEMORY_KEY) {
    storage = new MemoryStorage();
} else {
    throw Error("Nepodporovaná hodnota proměnné STORAGE: " + process.env.STORAGE + ", podporované jsou 'json', 'redis' nebo 'memory'");
}

export const storageReady: Promise<void> = storage.initialize
    ? storage.initialize()
    : Promise.resolve();

export default function getStorage(): StorageInterface {
    return storage;
}
