import fs from 'fs';
import path from 'path';

export interface SecretsOptions {
    cwd: string;
    ttl?: number;
    checkperiod?: number;
}

export class Secrets {
    storage: string;

    constructor({ cwd, ttl = 5 * 60 * 1000, checkperiod = 5 * 60 * 1000 }: SecretsOptions) {
        this.storage = path.join(cwd, '.secrets');

        if (!fs.existsSync(this.storage)) {
            fs.mkdirSync(this.storage);
        }

        const storage = this.storage;
        setTimeout(function cleanup() {
            for (const file of fs.readdirSync(storage)) {
                const { ctimeMs } = fs.statSync(path.join(storage, file));

                if (Date.now() > ctimeMs + ttl) {
                    fs.rmSync(path.join(storage, file));
                }
            }

            setTimeout(cleanup, checkperiod);
        }, checkperiod);
    }

    get = (key: string) => {
        if (fs.existsSync(path.join(this.storage, key))) {
            return fs.readFileSync(path.join(this.storage, key), 'utf8');
        }

        return undefined;
    };

    set = (key: string, value: string) => {
        fs.writeFileSync(path.join(this.storage, key), value, 'utf8');
    };
}
