import { type PlaylistEntry } from '@shared/ipc'
import { QUALITY_OPTIONS } from '../../lib/qualityOptions'
import { type MediaKind } from '../../store/downloads'
import { type AddEntry, type ChosenFormat } from '../../store/downloadTypes'

/** The download-bar state a playlist add reads to build its per-entry queue rows. */
export interface PlaylistAddContext {
  /** the bar's global kind (an entry with no override inherits this) */
  barKind: MediaKind
  /** the bar's global quality preset (used when an entry's kind matches barKind) */
  barQuality: string
  /** effective kind for an entry index: its override, else barKind */
  effKind: (index: number) => MediaKind
  /** exact per-item format the user probed + picked (video rows only) */
  itemFormats: Record<number, ChosenFormat>
}

/**
 * Map selected playlist entries to queue rows for a single `addMany` batch.
 * Each entry uses its own kind override; a video entry the user gave an exact
 * probed format downloads that format, otherwise quality falls back to the bar's
 * preset (when the kind matches) or that kind's default. Kept pure so the mapping
 * is unit-testable apart from the React hook.
 */
export function buildPlaylistAddEntries(
  chosen: PlaylistEntry[],
  ctx: PlaylistAddContext
): AddEntry[] {
  return chosen.map((e) => {
    const k = ctx.effKind(e.index)
    // A per-item exact format only makes sense for a video row (audio is a preset).
    const fmt = k === 'video' ? ctx.itemFormats[e.index] : undefined
    return {
      url: e.url,
      kind: k,
      quality: fmt ? fmt.label : k === ctx.barKind ? ctx.barQuality : QUALITY_OPTIONS[k][0],
      opts: {
        title: e.title,
        channel: e.uploader,
        durationLabel: e.durationLabel,
        ...(fmt ? { format: fmt } : {})
      }
    }
  })
}
