/**
 * Copyright-Free Image Search
 * ───────────────────────────
 * Searches Unsplash (primary) or Pexels (fallback) for free images.
 * Works without API keys — returns empty with a helpful message.
 */

export interface FreeImage {
  id: string;
  url: string;
  thumbnailUrl: string;
  altText: string;
  photographer: string;
  source: "unsplash" | "pexels";
  downloadUrl: string;
  width: number;
  height: number;
}

interface UnsplashResult {
  id: string;
  urls: { regular: string; small: string; raw: string };
  alt_description: string | null;
  user: { name: string };
  width: number;
  height: number;
  links: { download_location: string };
}

interface PexelsPhoto {
  id: number;
  src: { large: string; medium: string; original: string };
  alt: string | null;
  photographer: string;
  width: number;
  height: number;
}

async function searchUnsplash(query: string, page: number, perPage: number): Promise<FreeImage[]> {
  const key = process.env.UNSPLASH_ACCESS_KEY;
  if (!key) return [];

  const url = `https://api.unsplash.com/search/photos?query=${encodeURIComponent(query)}&per_page=${perPage}&page=${page}`;
  const res = await fetch(url, {
    headers: { Authorization: `Client-ID ${key}` },
    signal: AbortSignal.timeout(8000),
  });
  if (!res.ok) return [];

  const data = (await res.json()) as { results: UnsplashResult[] };
  return (data.results || []).map((r) => ({
    id: r.id,
    url: r.urls.regular,
    thumbnailUrl: r.urls.small,
    altText: r.alt_description || query,
    photographer: r.user.name,
    source: "unsplash" as const,
    downloadUrl: r.links.download_location,
    width: r.width,
    height: r.height,
  }));
}

async function searchPexels(query: string, page: number, perPage: number): Promise<FreeImage[]> {
  const key = process.env.PEXELS_API_KEY;
  if (!key) return [];

  const url = `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&per_page=${perPage}&page=${page}`;
  const res = await fetch(url, {
    headers: { Authorization: key },
    signal: AbortSignal.timeout(8000),
  });
  if (!res.ok) return [];

  const data = (await res.json()) as { photos: PexelsPhoto[] };
  return (data.photos || []).map((p) => ({
    id: String(p.id),
    url: p.src.large,
    thumbnailUrl: p.src.medium,
    altText: p.alt || query,
    photographer: p.photographer,
    source: "pexels" as const,
    downloadUrl: p.src.original,
    width: p.width,
    height: p.height,
  }));
}

export async function searchFreeImages(
  query: string,
  page: number = 1,
  perPage: number = 20,
): Promise<{ images: FreeImage[]; source: string | null; message: string | null }> {
  const hasUnsplash = !!process.env.UNSPLASH_ACCESS_KEY;
  const hasPexels = !!process.env.PEXELS_API_KEY;

  if (!hasUnsplash && !hasPexels) {
    return {
      images: [],
      source: null,
      message: "Configure UNSPLASH_ACCESS_KEY or PEXELS_API_KEY for free image search",
    };
  }

  // Try Unsplash first (higher quality)
  if (hasUnsplash) {
    try {
      const images = await searchUnsplash(query, page, perPage);
      if (images.length > 0) return { images, source: "unsplash", message: null };
    } catch { /* fallthrough to Pexels */ }
  }

  // Fallback to Pexels
  if (hasPexels) {
    try {
      const images = await searchPexels(query, page, perPage);
      return { images, source: "pexels", message: null };
    } catch { /* return empty */ }
  }

  return { images: [], source: null, message: "Image search returned no results" };
}
