/**
 * Extract only the pure timestamp filename (e.g. "1789980758752.mp4")
 * from any input path or URL (e.g. "http://localhost:5000/uploads/videos/16by9_1789980758752.mp4"
 * or "/uploads/videos/16by9_1789980758752.mp4" or "d:\path\to\16by9_1789980758752.mp4").
 * Preserves external non-local URLs (e.g. YouTube, Vimeo, external CDNs).
 */
export function extractFilename(val?: string | null): string {
  if (!val || typeof val !== 'string') return '';
  const trimmed = val.trim();
  if (!trimmed) return '';

  // If external non-localhost HTTP/HTTPS link (e.g. YouTube, Vimeo, external CDN)
  if (
    (trimmed.startsWith('http://') || trimmed.startsWith('https://')) &&
    !trimmed.includes('/uploads/') &&
    !trimmed.includes('localhost:5000') &&
    !trimmed.includes('127.0.0.1:5000')
  ) {
    return trimmed;
  }

  let raw = trimmed;
  if (raw.includes('/uploads/')) {
    const parts = raw.split('/uploads/');
    const afterUploads = parts[parts.length - 1];
    const subParts = afterUploads.split(/[\/\\]/);
    raw = subParts[subParts.length - 1];
  } else if (raw.includes('/') || raw.includes('\\')) {
    const parts = raw.split(/[\/\\]/);
    raw = parts[parts.length - 1];
  }

  // Extract pure timestamp filename if formatted like "16by9_1789980758752.mp4"
  const match = raw.match(/.*?(\d{10,}\.[a-zA-Z0-9]+)$/);
  if (match && match[1]) {
    return match[1];
  }

  return raw;
}

/**
 * Build full media URL (e.g., http://localhost:5000/uploads/videos/1789980758752.mp4) from stored filename
 */
export function getMediaUrl(val?: string | null, category: 'videos' | 'pdfs' | 'images' | 'documents' = 'videos'): string {
  if (!val || typeof val !== 'string') return '';
  const trimmed = val.trim();
  if (!trimmed) return '';

  // External URLs
  if (
    (trimmed.startsWith('http://') || trimmed.startsWith('https://')) &&
    !trimmed.includes('/uploads/') &&
    !trimmed.includes('localhost:5000') &&
    !trimmed.includes('127.0.0.1:5000')
  ) {
    return trimmed;
  }

  const apiBase = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000/api';

  // If S3 object key (e.g., lessons-videos/1790253121493-4j8e88-testing-video-2.mp4)
  if (!trimmed.includes('/uploads/') && (trimmed.startsWith('lessons-videos/') || trimmed.startsWith('pdfs/') || (trimmed.includes('-') && trimmed.includes('/')))) {
    return `${apiBase}/videos/stream?key=${encodeURIComponent(trimmed)}`;
  }

  const filename = extractFilename(trimmed);
  if (!filename) return '';

  let subFolder = category;
  const ext = filename.split('.').pop()?.toLowerCase() || '';
  if (['mp4', 'mkv', 'webm', 'mov', 'avi'].includes(ext)) {
    subFolder = 'videos';
  } else if (['pdf'].includes(ext)) {
    subFolder = 'pdfs';
  } else if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'].includes(ext)) {
    subFolder = 'images';
  }

  const baseUrl = apiBase.replace(/\/api\/?$/, '');

  return `${baseUrl}/uploads/${subFolder}/${filename}`;
}
