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

const uploadDir = './data/avatar';

export async function saveFile(key: string, file: Buffer | File) {
  if (!uploadDir) {
    throw new Error('Upload directory not found');
  }

  const fileBuffer =
    file instanceof File ? Buffer.from(await file.arrayBuffer()) : file;

  const filePath = path.join(uploadDir, key);

  try {
    await fs.mkdir(uploadDir, { recursive: true });
    await writeFile(filePath, fileBuffer);
    return key;
  } catch (error) {
    console.error(`Error saving file: ${key}`, error);
    throw new Error(
      `Failed to save file: ${error instanceof Error ? error.message : 'Unknown error'}`,
    );
  }
}
