import { SentenceToken } from '../stores/sentenceStore';
import { MediaKind } from '../types/term';

export interface PlaylistItem {
  tokenId: string;
  termId: string;
  displayText: string;
  videoUrl: string | null;
  durationMs: number | null;
}

/**
 * Build a playlist from sentence tokens
 * Extracts video media from each token's term
 */
export function buildPlaylist(tokens: SentenceToken[]): PlaylistItem[] {
  return tokens.map(token => {
    // Get first video media for the term
    const videoMedia = token.term.media?.find(m => m.kind === MediaKind.VIDEO);

    return {
      tokenId: token.id,
      termId: token.termId,
      displayText: token.displayText,
      videoUrl: videoMedia?.url || null,
      durationMs: videoMedia?.durationMs || null,
    };
  });
}

/**
 * Convert relative URL to absolute URL
 * Handles both relative and absolute URLs
 */
export function getVideoUrl(relativeUrl: string | null): string | null {
  if (!relativeUrl) return null;

  // If already absolute URL, return as-is
  if (relativeUrl.startsWith('http')) return relativeUrl;

  // Construct full URL using backend base URL
  const baseUrl = import.meta.env.VITE_API_URL !== undefined ? import.meta.env.VITE_API_URL : 'http://localhost:3000';
  return `${baseUrl}${relativeUrl}`;
}

