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

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

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
 */
export function getAvatarUrl(
  photos?: PhotoAttachment[],
  fallbackId?: number | string,
  name?: string
): string {
  const photoUrl = getPhotoUrl(photos);
  
  if (photoUrl) {
    return photoUrl;
  }
  
  // Fallback to UI avatars if name is provided
  if (name) {
    return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=random`;
  }
  
  // Final fallback
  return `https://ui-avatars.com/api/?name=User&background=random`;
}

/**
 * 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;
}

