import { writeFile, mkdir } from 'fs/promises';
import { join } from 'path';

const ALLOWED_IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif']);

function sanitizePath(segment: string): string {
    if (/\.\.|[/\\]/.test(segment) || segment.startsWith('.')) {
        throw new Error('Path traversal detected: invalid path segment');
    }
    if (!segment) throw new Error('Invalid path segment');
    return segment;
}

export async function uploadImage(file: File, folder: string = 'menu'): Promise<string> {
    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);

    const rawExt = (file.name.split('.').pop() || '').toLowerCase();
    if (!ALLOWED_IMAGE_EXTENSIONS.has(rawExt)) {
        throw new Error(
            `File type ".${rawExt}" is not allowed. Permitted types: ${[...ALLOWED_IMAGE_EXTENSIONS].join(', ')}.`
        );
    }
    const ext = rawExt;
    const safeFolder = sanitizePath(folder);
    const filename = `${crypto.randomUUID()}.${ext}`;
    const relativePath = `/uploads/${safeFolder}/${filename}`;
    const absolutePath = join(process.cwd(), 'public', 'uploads', safeFolder, filename);

    await mkdir(join(process.cwd(), 'public', 'uploads', safeFolder), { recursive: true });

    await writeFile(absolutePath, buffer);

    return relativePath;
}
