import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";

const OUTPUT_DIR = "output";

function sanitizeFileNamePart(value: string): string {
	return value
		.trim()
		.toLowerCase()
		.replace(/[^a-z0-9]+/g, "-")
		.replace(/^-+|-+$/g, "")
		.slice(0, 60);
}

function mediaTypeToExtension(mediaType: string): string {
	switch (mediaType) {
		case "image/png":
			return "png";
		case "image/jpeg":
			return "jpg";
		case "image/webp":
			return "webp";
		case "image/gif":
			return "gif";
		default:
			return "bin";
	}
}

function createTimestampFileName(mediaType: string, name?: string): string {
	const extension = mediaTypeToExtension(mediaType);
	const timestamp = new Date().toISOString().replace(/[.:]/g, "-");
	const prefix = name ? `${sanitizeFileNamePart(name)}-` : "";
	return `${prefix}${timestamp}.${extension}`;
}

export async function saveImage(
	bytes: Uint8Array,
	mediaType: string,
	name?: string,
): Promise<string> {
	await mkdir(OUTPUT_DIR, { recursive: true });

	const filePath = join(OUTPUT_DIR, createTimestampFileName(mediaType, name));
	await writeFile(filePath, bytes);

	return filePath;
}
