import { getSyncPlayApi } from '@jellyfin/sdk/lib/utils/api/sync-play-api'
import { jellyfinClient } from '../api/jellyfin'

/**
 * REST wrappers around Jellyfin SyncPlay. The server keeps the group
 * state - we just send commands and read the membership list. Real-time
 * pushes come through the WebSocket subscription in `syncplay-socket.ts`.
 */

export interface SyncPlayGroup {
  groupId: string
  groupName: string
  participantCount: number
}

function requireApi() {
  const api = jellyfinClient.getApi()
  if (!api) throw new Error('Not authenticated')
  return api
}

export async function listGroups(): Promise<SyncPlayGroup[]> {
  const api = jellyfinClient.getApi()
  if (!api) return []
  try {
    const res = await getSyncPlayApi(api).syncPlayGetGroups()
    return (res.data || []).map(g => ({
      groupId: g.GroupId || '',
      groupName: g.GroupName || 'Untitled group',
      participantCount: g.Participants?.length || 0,
    }))
  } catch {
    return []
  }
}

export async function createGroup(name: string): Promise<SyncPlayGroup | null> {
  const res = await getSyncPlayApi(requireApi()).syncPlayCreateGroup({
    newGroupRequestDto: { GroupName: name },
  })
  const g = res.data
  if (!g?.GroupId) return null
  return {
    groupId: g.GroupId,
    groupName: g.GroupName || name,
    participantCount: g.Participants?.length || 1,
  }
}

export async function joinGroup(groupId: string): Promise<void> {
  await getSyncPlayApi(requireApi()).syncPlayJoinGroup({
    joinGroupRequestDto: { GroupId: groupId },
  })
}

export async function leaveGroup(): Promise<void> {
  await getSyncPlayApi(requireApi()).syncPlayLeaveGroup()
}

export async function sendPause(): Promise<void> {
  await getSyncPlayApi(requireApi()).syncPlayPause()
}

export async function sendUnpause(): Promise<void> {
  await getSyncPlayApi(requireApi()).syncPlayUnpause()
}

export async function sendSeek(positionTicks: number): Promise<void> {
  await getSyncPlayApi(requireApi()).syncPlaySeek({
    seekRequestDto: { PositionTicks: positionTicks },
  })
}

/**
 * Tell the server the current item + position. Used by the host when
 * they create a party so that joiners get pushed the right item via
 * the PlayQueue WS update.
 */
export async function setNewQueue(itemId: string, positionTicks: number): Promise<void> {
  await getSyncPlayApi(requireApi()).syncPlaySetNewQueue({
    playRequestDto: {
      PlayingQueue: [itemId],
      PlayingItemPosition: 0,
      StartPositionTicks: positionTicks,
    },
  })
}
