import api from './api';

export type YouTubeVideo = {
  video_id: string;
  title: string;
  thumbnail_url: string;
  views_text?: string;
  views?: number;
  published_text?: string;
  published_date?: string; // YYYY-MM-DD
};

export type YouTubeChannelPayload = {
  channel: string;
  channel_url: string;
  subscribers_text?: string;
  subscribers?: number;
  videos: YouTubeVideo[];
};

export const getCachedYouTube = async (): Promise<YouTubeChannelPayload | null> => {
  try {
    const res = await api.get('/youtube/videos');
    const primary = res?.data as YouTubeChannelPayload | undefined;
    const hasVideos = Array.isArray(primary?.videos) && (primary!.videos.length > 0);
    // If backend responded with 204 or empty payload, fall back to the static cached JSON
    if (res.status === 204 || !primary || !hasVideos) {
      const fallback = await fetchStaticYouTubeCache();
      return sortByPublishedDate(fallback);
    }
    return sortByPublishedDate(primary) as YouTubeChannelPayload;
  } catch {
    // Fallback: fetch static cached JSON directly from backend /cache path to avoid stressing external API
    return await fetchStaticYouTubeCache();
  }
};

// Helper: fetch static cached JSON from /cache/prefetch
const fetchStaticYouTubeCache = async (): Promise<YouTubeChannelPayload | null> => {
  try {
    // Determine backend origin from env config similar to HomePage resolve logic
    const base = (process.env.REACT_APP_API_BASE_URL || process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1');
    const u = new URL(base);
    // Force path to backend-exposed cache file
    u.pathname = '/cache/prefetch/youtube_channel.json';
    const resp = await fetch(u.toString(), { cache: 'no-cache' });
    if (!resp.ok) return null;
    const data = (await resp.json()) as YouTubeChannelPayload;
    return sortByPublishedDate(data);
  } catch {
    return null;
  }
};

// Helper: ensure videos are sorted by most recent published_date
const sortByPublishedDate = (payload: YouTubeChannelPayload | null | undefined): YouTubeChannelPayload | null => {
  if (!payload || !Array.isArray(payload.videos)) return payload ?? null;
  const copy: YouTubeChannelPayload = { ...payload, videos: [...payload.videos] };
  copy.videos.sort((a, b) => {
    const ta = Date.parse(a.published_date || '') || 0;
    const tb = Date.parse(b.published_date || '') || 0;
    return tb - ta; // newest first
  });
  return copy;
};
