import type { SocialPlatform } from "@/config/social-posts";

export type EmbedData =
  | { type: "iframe"; src: string }
  | { type: "html"; html: string }
  | { type: "instagram_native"; url: string }
  | {
      type: "instagram_card";
      url: string;
      imageUrl: string;
      caption: string | null;
    }
  | { type: "fallback"; url: string };

export interface SocialEmbedItem {
  platform: SocialPlatform;
  url: string;
  embed: EmbedData;
}

/**
 * Construit l'URL iframe pour un post Facebook.
 * show_text=true affiche le texte sous l'image.
 * width=400, height=700 pour remplir la carte et afficher le post sans rognage.
 * Le post doit être public pour être affiché.
 */
function getFacebookEmbedUrl(postUrl: string): string {
  return `https://www.facebook.com/plugins/post.php?href=${encodeURIComponent(postUrl)}&width=400&show_text=true&height=700`;
}

/**
 * Tente l'oEmbed Instagram pour obtenir image + légende et afficher une carte.
 * Si l'API ne renvoie pas thumbnail_url/title, on utilise l'embed natif (blockquote).
 */
async function fetchInstagramEmbed(url: string): Promise<EmbedData> {
  try {
    const res = await fetch(
      `https://api.instagram.com/oembed?url=${encodeURIComponent(url)}&omitscript=true`,
      { next: { revalidate: 3600 } }
    );
    if (!res.ok) return { type: "instagram_native", url };
    const data = (await res.json()) as {
      thumbnail_url?: string;
      title?: string;
      html?: string;
    };
    if (data.thumbnail_url) {
      return {
        type: "instagram_card",
        url,
        imageUrl: data.thumbnail_url,
        caption: data.title ?? null,
      };
    }
    return { type: "instagram_native", url };
  } catch {
    return { type: "instagram_native", url };
  }
}

/**
 * Récupère l'embed TikTok via oEmbed.
 */
async function fetchTikTokEmbed(url: string): Promise<EmbedData> {
  try {
    const res = await fetch(
      `https://www.tiktok.com/oembed?url=${encodeURIComponent(url)}`,
      { next: { revalidate: 3600 } }
    );
    if (!res.ok) return { type: "fallback", url };
    const data = (await res.json()) as { html?: string };
    if (data.html) return { type: "html", html: data.html };
    return { type: "fallback", url };
  } catch {
    return { type: "fallback", url };
  }
}

/**
 * Pour chaque entrée de la config, récupère les données d'embed (iframe ou HTML oEmbed).
 * Utilisé côté serveur pour préremplir les embeds sans exposer de clés API.
 */
export async function getSocialEmbeds(
  config: Array<{ platform: SocialPlatform; url: string }>
): Promise<SocialEmbedItem[]> {
  const results: SocialEmbedItem[] = [];

  for (const item of config) {
    let embed: EmbedData;

    switch (item.platform) {
      case "facebook":
        embed = { type: "iframe", src: getFacebookEmbedUrl(item.url) };
        break;
      case "instagram":
        embed = await fetchInstagramEmbed(item.url);
        break;
      case "tiktok":
        embed = await fetchTikTokEmbed(item.url);
        break;
      default:
        embed = { type: "fallback", url: item.url };
    }

    results.push({ platform: item.platform, url: item.url, embed });
  }

  return results;
}
