/**
 * Origin Private File System (OPFS) storage for custom song files.
 *
 * Structure: /songs/{songId}/{filename}
 */

async function getSongsDir(): Promise<FileSystemDirectoryHandle> {
  const root = await navigator.storage.getDirectory()
  return root.getDirectoryHandle('songs', { create: true })
}

export async function saveSongFiles(
  songId: string,
  files: { name: string; data: ArrayBuffer }[],
): Promise<void> {
  const songsDir = await getSongsDir()
  const songDir = await songsDir.getDirectoryHandle(songId, { create: true })

  for (const file of files) {
    const handle = await songDir.getFileHandle(file.name, { create: true })
    const writable = await handle.createWritable()
    await writable.write(file.data)
    await writable.close()
  }
}

export async function loadSongFile(songId: string, fileName: string): Promise<File> {
  const songsDir = await getSongsDir()
  const songDir = await songsDir.getDirectoryHandle(songId)
  const handle = await songDir.getFileHandle(fileName)
  return handle.getFile()
}

export async function loadAllSongFiles(songId: string): Promise<Map<string, File>> {
  const songsDir = await getSongsDir()
  const songDir = await songsDir.getDirectoryHandle(songId)
  const files = new Map<string, File>()
  for await (const [name, handle] of songDir.entries()) {
    if (handle.kind === 'file') {
      files.set(name, await handle.getFile())
    }
  }
  return files
}

export async function deleteSongFiles(songId: string): Promise<void> {
  const songsDir = await getSongsDir()
  await songsDir.removeEntry(songId, { recursive: true })
}

export async function listStoredSongIds(): Promise<string[]> {
  try {
    const songsDir = await getSongsDir()
    const ids: string[] = []
    for await (const [name, handle] of songsDir.entries()) {
      if (handle.kind === 'directory') {
        ids.push(name)
      }
    }
    return ids
  } catch {
    return []
  }
}
