/**
 * Helper functions for extracting photo URLs from photo associations
 */

import type { WebsitePhotos } from '../types/api/website-photos';

/** Video file extensions treated as video (match backend ExternalPhotoService.video_url?) */
const VIDEO_EXTENSIONS = ['.mp4', '.mov', '.webm', '.m4v', '.avi', '.mkv', '.flv', '.wmv'];

/**
 * True if the URL looks like a video by path extension. Used to avoid using video URLs in img src.
 */
export function isVideoUrl(url: string | null | undefined): boolean {
  if (!url || typeof url !== 'string') return false;
  const path = url.split('?')[0] ?? '';
  const ext = path.slice(path.lastIndexOf('.')).toLowerCase();
  return VIDEO_EXTENSIONS.includes(ext);
}

export interface PhotoAttachment {
  id: number;
  photo: {
    id: number;
    title: string;
    thumbnail_url?: string;
    medium_url?: string;
    large_url?: string;
    original_url?: string;
  };
  featured: boolean;
  sort_order: number;
}

/**
 * Get the best available photo URL from a photos array
 * Priority: featured photo > first photo > fallback
 */
export function getPhotoUrl(
  photos?: PhotoAttachment[]
): string | null {
  // Priority 1: Featured photo from photos array
  if (photos && photos.length > 0) {
    const featuredPhoto = photos.find(pa => pa.featured);
    const photoToUse = featuredPhoto || photos[0];
    const photo = photoToUse.photo;
    
    if (photo) {
      return photo.large_url || photo.medium_url || photo.thumbnail_url || photo.original_url || null;
    }
  }
  
  // Fallback (gradient or null)
  return null;
}

/**
 * Get avatar URL for team members or authors.
 * Returns a URL only when there is a real photo in attachments; otherwise null.
 * Callers should use PhotoWithFallback (gradient fallback) or Avatar with initials when null.
 */
/** Optional fallbackId/name reserved for future use (e.g. deterministic fallback). */
/* eslint-disable @typescript-eslint/no-unused-vars -- _fallbackId, _name reserved for API */
export function getAvatarUrl(
  photos?: PhotoAttachment[],
  _fallbackId?: number | string,
  _name?: string
): string | null {
  return getPhotoUrl(photos);
}
/* eslint-enable @typescript-eslint/no-unused-vars */

/**
 * Get featured image URL for blog posts
 */
export function getFeaturedImageUrl(
  photos?: PhotoAttachment[]
): string | null {
  return getPhotoUrl(photos);
}

/**
 * Get logo URL from website_photos API (which aggregates from account_photos)
 * 
 * The website_photos API endpoint returns logos from account_photos with photo_type: 'logo',
 * with industry fallback. This is the primary and only source for logos.
 * 
 * Returns undefined if no logo is available (for PhotoWithFallback gradient fallback)
 */
export function getLogoUrl(
  websitePhotos?: WebsitePhotos | null
): string | undefined {
  if (websitePhotos?.logo?.url) {
    return websitePhotos.logo.url;
  }
  
  return undefined;
}

