import { jellyfinClient, getSessionApi } from '../api/jellyfin'

/**
 * Remote-control / cast helpers built on top of Jellyfin's Sessions API.
 *
 * The server tracks every connected client (web, mobile, DLNA-bridged TV,
 * Chromecast via plugin, etc.) as a session. Any session that's flagged
 * `SupportsRemoteControl` can receive Play commands from another client -
 * so "casting" here is really "tell session X to play item Y".
 *
 * No native DLNA discovery from this app. We just enumerate what the
 * server already knows about.
 */

export interface CastTarget {
  sessionId: string
  deviceName: string
  client: string
  userName: string | null
  mediaTypes: string[]
}

function getDeviceId(): string | null {
  return jellyfinClient.getApi()?.deviceInfo?.id ?? null
}

export async function listCastTargets(mediaType?: string): Promise<CastTarget[]> {
  const api = jellyfinClient.getApi()
  if (!api) return []
  const self = getDeviceId()
  const res = await getSessionApi(api).getSessions()
  const sessions = res.data || []
  return sessions
    .filter(s => {
      if (!s.SupportsRemoteControl) return false
      if (!s.Id) return false
      if (self && s.DeviceId === self) return false
      if (mediaType && s.PlayableMediaTypes && s.PlayableMediaTypes.length > 0) {
        return s.PlayableMediaTypes.some(t => String(t).toLowerCase() === mediaType.toLowerCase())
      }
      return true
    })
    .map(s => ({
      sessionId: s.Id!,
      deviceName: s.DeviceName || 'Unknown device',
      client: s.Client || '',
      userName: s.UserName ?? null,
      mediaTypes: (s.PlayableMediaTypes || []).map(String),
    }))
}

export async function sendToSession(sessionId: string, itemId: string): Promise<void> {
  const api = jellyfinClient.getApi()
  if (!api) throw new Error('Not authenticated')
  await getSessionApi(api).play({
    sessionId,
    playCommand: 'PlayNow' as const,
    itemIds: [itemId],
  })
}
