/**
 * Strapi API services
 */

import axiosInstance from '@/lib/axios';

// Types for Strapi responses
export interface StrapiMediaFormat {
  name: string;
  hash: string;
  ext: string;
  mime: string;
  width: number;
  height: number;
  size: number;
  url: string;
}

export interface StrapiMedia {
  id: number;
  name: string;
  alternativeText: string | null;
  caption: string | null;
  width: number;
  height: number;
  formats: {
    thumbnail?: StrapiMediaFormat;
    small?: StrapiMediaFormat;
    medium?: StrapiMediaFormat;
    large?: StrapiMediaFormat;
  } | null;
  hash: string;
  ext: string;
  mime: string;
  size: number;
  url: string;
  previewUrl: string | null;
  provider: string;
  createdAt: string;
  updatedAt: string;
}

export interface VideoUrlData {
  id: number;
  background: StrapiMedia;
  createdAt: string;
  updatedAt: string;
  publishedAt: string;
}

export interface StrapiSingleTypeResponse<T> {
  data: T;
  meta: Record<string, any>;
}

/**
 * Fetch the video-url single type data from Strapi
 */
export async function getVideoUrl(): Promise<VideoUrlData | null> {
  try {
    const response = await axiosInstance.get<StrapiSingleTypeResponse<VideoUrlData>>(
      '/api/video-url',
      {
        params: {
          populate: '*', // Populate all relations including the background media
        },
      }
    );

    return response.data.data;
  } catch (error) {
    console.error('Error fetching video URL:', error);
    return null;
  }
}

/**
 * Get the full URL for a Strapi media file
 */
export function getMediaUrl(media: StrapiMedia | null | undefined): string | null {
  if (!media || !media.url) return null;
  
  // If the URL is already absolute, return it as is
  if (media.url.startsWith('http://') || media.url.startsWith('https://')) {
    return media.url;
  }
  
  // Otherwise, prepend the API URL
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:1337';
  return `${apiUrl}${media.url}`;
}

/**
 * Get a specific format URL for a Strapi media file
 */
export function getMediaFormatUrl(
  media: StrapiMedia | null | undefined,
  format: 'thumbnail' | 'small' | 'medium' | 'large' = 'medium'
): string | null {
  if (!media) return null;
  
  // Try to get the specific format
  const formatData = media.formats?.[format];
  if (formatData && formatData.url) {
    // If the URL is already absolute, return it as is
    if (formatData.url.startsWith('http://') || formatData.url.startsWith('https://')) {
      return formatData.url;
    }
    
    // Otherwise, prepend the API URL
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:1337';
    return `${apiUrl}${formatData.url}`;
  }
  
  // Fallback to the original media URL
  return getMediaUrl(media);
}

