import * as fs from "node:fs";
import * as Path from "node:path";
import { pipeline } from "node:stream/promises";
import config from "@/config/index.js";

export class InternalStorage {
	public static resolvePath = (key: string) =>
		Path.resolve(config.mediaDir, key);

	public static read(key: string) {
		return fs.createReadStream(InternalStorage.resolvePath(key));
	}

	public static async saveFromPath(key: string, srcPath: string) {
		fs.mkdirSync(config.mediaDir, { recursive: true });
		await pipeline(
			fs.createReadStream(srcPath),
			fs.createWriteStream(InternalStorage.resolvePath(key)),
		);
		return `${config.url}/files/${key}`;
	}

	public static saveFromBuffer(key: string, data: Buffer) {
		fs.mkdirSync(config.mediaDir, { recursive: true });
		fs.writeFileSync(InternalStorage.resolvePath(key), data);
		return `${config.url}/files/${key}`;
	}

	public static del(key: string) {
		fs.unlink(InternalStorage.resolvePath(key), () => {});
	}
}
