export const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8001';
import https from 'https';

const agent = new https.Agent({
  rejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED === 'true',
});


export async function fetchHomepageData(host: string) {
  try {
    const res = await fetch(`${API_URL}/api/homepage?domain=${encodeURIComponent(host)}`, {
      next: { revalidate: 0,}, // Cache for 60 seconds,
    });

    if (!res.ok) {
        return null;
    }
    return await res.json();
  } catch (error) {
    console.error('Error fetching homepage data:', error);
    return null;
  }
}

export async function fetchPosts(host: string, page: number = 1, category?: string) {
  try {
    let url = `${API_URL}/api/posts?domain=${encodeURIComponent(host)}&page=${page}`;
    if (category) {
      url += `&category=${encodeURIComponent(category)}`;
    }
    const res = await fetch(url, {
      next: { revalidate: 60 }
    });
    if (!res.ok) {
        return null;
    }
    return await res.json();
  } catch (error) {
    console.error('Error fetching posts:', error);
    return null;
  }
}

export async function fetchPostDetails(host: string, slug: string) {
  try {
    const res = await fetch(`${API_URL}/api/posts/${encodeURIComponent(slug)}?domain=${encodeURIComponent(host)}`, {
      next: { revalidate: 60 }
    });
    if (!res.ok) {
        return null;
    }
    return await res.json();
  } catch (error) {
    console.error('Error fetching post:', error);
    return null;
  }
}

export async function fetchBrandDetails(host: string, urlIdentifier: string, slug: string) {
  try {
    const res = await fetch(`${API_URL}/api/brands/${encodeURIComponent(urlIdentifier)}/${encodeURIComponent(slug)}?domain=${encodeURIComponent(host)}`, {
      next: { revalidate: 60 }
    });
    if (!res.ok) {
        return null;
    }
    return await res.json();
  } catch (error) {
    console.error('Error fetching brand:', error);
    return null;
  }
}

export function getMediaUrl(mediaPath: string | null) {
  if (!mediaPath) return '';
  if (mediaPath.startsWith('http')) return mediaPath;
  return `/storage/${mediaPath}`;
}
