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

export function computeHash(audioBuffer: Buffer): string {
  return createHash("sha256").update(audioBuffer).digest("hex");
}

function getUserDir(userId: string): string {
  return join(process.cwd(), "uploads", "voiceprint", userId);
}

export async function saveAudio(
  userId: string,
  audioBuffer: Buffer,
): Promise<{ hash: string; filePath: string }> {
  const hash = computeHash(audioBuffer);
  const userDir = getUserDir(userId);
  if (!existsSync(userDir)) {
    await mkdir(userDir, { recursive: true });
  }
  const filePath = join(userDir, `${hash}.wav`);
  await writeFile(filePath, audioBuffer);
  return { hash, filePath };
}

export function getAudioUrl(userId: string, audioHash: string): string {
  return `/uploads/voiceprint/${userId}/${audioHash}.wav`;
}

export async function deleteFile(filePath: string): Promise<void> {
  try {
    await unlink(filePath);
  } catch {
    // File may not exist
  }
}

export async function deleteAudio(userId: string, audioHash: string): Promise<void> {
  const filePath = join(getUserDir(userId), `${audioHash}.wav`);
  await deleteFile(filePath);
}
