import { getSoundFileURL } from "./utils";
import { CAM_BASE } from "./config";
import type { SoundUploadValue } from "../types/types";

export function resolveSoundSource(
  selected: string | undefined,
  soundOptions: SoundUploadValue[] | undefined
): { type: "uploaded"; url: string } | { type: "builtin"; url: string } | undefined {
  if (!selected) return undefined;

  const isFile = selected.endsWith(".mp3") || selected.endsWith(".wav");

  if (isFile) {
    const match = soundOptions?.find((o) => o.soundFileName === selected);
    const version = match?.uploadedAt ?? 0;
    const url = `${CAM_BASE}/Mobile/${encodeURIComponent(selected)}?v=${version}`;
    return { type: "uploaded", url };
  }

  const builtin = getSoundFileURL(selected);
  if (builtin) return { type: "builtin", url: builtin };

  return undefined;
}
