/**
 * Diffusion des événements sur les réseaux — serveur uniquement.
 * À charger dans un handler : `await import("@/lib/social.server")`.
 *
 * Secrets requis (Lovable Cloud → Secrets) :
 *   PUBLIC_SITE_URL        ex. https://www.vespercannes.com (images absolues)
 *   META_PAGE_ID           ID de la Page Facebook
 *   META_PAGE_ACCESS_TOKEN jeton de Page longue durée
 *                          (pages_manage_posts, instagram_content_publish)
 *   META_IG_USER_ID        ID du compte Instagram professionnel lié à la Page
 *   META_GRAPH_VERSION     optionnel, défaut v21.0
 *
 * Wyylde n'a pas d'API publique : le canal est marqué « manual » et l'admin
 * copie le kit (légende + visuel) en un clic.
 */
import type { SupabaseClient } from "@supabase/supabase-js";
import type { Database } from "@/integrations/supabase/types";
import { buildCaption, type Channel, type PublicationStatus } from "./social";

type EventRow = Database["public"]["Tables"]["events"]["Row"];

export type ChannelResult = {
  channel: Channel;
  status: PublicationStatus;
  external_id?: string | null;
  external_url?: string | null;
  error?: string | null;
};

function env(name: string): string | undefined {
  const v = process.env[name];
  return v && v.trim() ? v.trim() : undefined;
}

function graphBase(): string {
  return `https://graph.facebook.com/${env("META_GRAPH_VERSION") ?? "v21.0"}`;
}

function absoluteUrl(url: string): string {
  if (/^https?:\/\//i.test(url)) return url;
  const base = env("PUBLIC_SITE_URL");
  if (!base) throw new Error("PUBLIC_SITE_URL manquant : impossible de rendre l'image publique.");
  return new URL(url, base).toString();
}

type GraphJson = {
  id?: string;
  post_id?: string;
  permalink?: string;
  status_code?: string;
  error?: { message?: string };
};

async function graph(
  method: "GET" | "POST",
  path: string,
  params: Record<string, string>,
): Promise<GraphJson> {
  const qs = new URLSearchParams(params);
  const url = `${graphBase()}/${path}`;
  const res =
    method === "GET"
      ? await fetch(`${url}?${qs.toString()}`)
      : await fetch(url, { method: "POST", body: qs });
  const json = (await res.json().catch(() => ({}))) as GraphJson;
  if (!res.ok || json.error) {
    throw new Error(json.error?.message ?? `Meta API HTTP ${res.status}`);
  }
  return json;
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

async function publishFacebook(ev: EventRow, caption: string): Promise<ChannelResult> {
  const pageId = env("META_PAGE_ID");
  const token = env("META_PAGE_ACCESS_TOKEN");
  if (!pageId || !token) {
    return {
      channel: "facebook",
      status: "error",
      error: "Configuration Meta manquante (META_PAGE_ID / META_PAGE_ACCESS_TOKEN).",
    };
  }
  if (ev.image_url) {
    const json = await graph("POST", `${pageId}/photos`, {
      url: absoluteUrl(ev.image_url),
      caption,
      access_token: token,
    });
    const postId = json.post_id ?? json.id ?? null;
    return {
      channel: "facebook",
      status: "published",
      external_id: postId,
      external_url: postId ? `https://www.facebook.com/${postId}` : null,
    };
  }
  const json = await graph("POST", `${pageId}/feed`, {
    message: caption,
    link: absoluteUrl("/evenements"),
    access_token: token,
  });
  return {
    channel: "facebook",
    status: "published",
    external_id: json.id ?? null,
    external_url: json.id ? `https://www.facebook.com/${json.id}` : null,
  };
}

async function publishInstagram(ev: EventRow, caption: string): Promise<ChannelResult> {
  const igId = env("META_IG_USER_ID");
  const token = env("META_PAGE_ACCESS_TOKEN");
  if (!igId || !token) {
    return {
      channel: "instagram",
      status: "error",
      error: "Configuration Meta manquante (META_IG_USER_ID / META_PAGE_ACCESS_TOKEN).",
    };
  }
  if (!ev.image_url) {
    return {
      channel: "instagram",
      status: "skipped",
      error: "Instagram exige un visuel : ajoutez une image.",
    };
  }
  // 1. Conteneur média (image JPEG publique obligatoire).
  const container = await graph("POST", `${igId}/media`, {
    image_url: absoluteUrl(ev.image_url),
    caption,
    access_token: token,
  });
  if (!container.id) throw new Error("Instagram : conteneur média non créé.");

  // 2. Attendre que Meta ait traité l'image.
  for (let i = 0; i < 6; i++) {
    const s = await graph("GET", container.id, { fields: "status_code", access_token: token });
    if (s.status_code === "FINISHED") break;
    if (s.status_code === "ERROR")
      throw new Error("Instagram : l'image a été refusée (format ou taille).");
    await sleep(1500);
  }

  // 3. Publication.
  const media = await graph("POST", `${igId}/media_publish`, {
    creation_id: container.id,
    access_token: token,
  });
  let permalink: string | null = null;
  if (media.id) {
    const info = await graph("GET", media.id, { fields: "permalink", access_token: token }).catch(
      () => null,
    );
    permalink = info?.permalink ?? null;
  }
  return {
    channel: "instagram",
    status: "published",
    external_id: media.id ?? null,
    external_url: permalink,
  };
}

function wyyldeKit(): ChannelResult {
  return {
    channel: "wyylde",
    status: "manual",
    error: null,
    external_url:
      "https://app.wyylde.com/fr-fr/page/9953d990-661d-11e6-b3b6-83d744cc09db/vesper-bar-klubber-cannes/wall",
  };
}

/**
 * Diffuse un événement sur ses canaux cochés et enregistre le résultat.
 * Un canal déjà publié n'est pas republié (pas de doublon), sauf `force`.
 * N'échoue jamais : chaque erreur est stockée sur le canal concerné.
 */
export async function publishEvent(
  supabase: SupabaseClient<Database>,
  ev: EventRow,
  opts: { force?: boolean | undefined; only?: Channel[] | undefined } = {},
): Promise<ChannelResult[]> {
  const caption = ev.social_caption?.trim() || buildCaption(ev);

  const wanted: Channel[] = [];
  if (ev.publish_instagram) wanted.push("instagram");
  if (ev.publish_facebook) wanted.push("facebook");
  if (ev.publish_wyylde) wanted.push("wyylde");
  const targets = opts.only ? wanted.filter((c) => opts.only!.includes(c)) : wanted;

  const { data: existing } = await supabase
    .from("event_publications")
    .select("channel, status")
    .eq("event_id", ev.id);
  const alreadyDone = new Set(
    (existing ?? []).filter((p) => p.status === "published").map((p) => p.channel),
  );

  const results: ChannelResult[] = [];
  for (const channel of targets) {
    if (!opts.force && alreadyDone.has(channel)) continue;
    let result: ChannelResult;
    try {
      result =
        channel === "instagram"
          ? await publishInstagram(ev, caption)
          : channel === "facebook"
            ? await publishFacebook(ev, caption)
            : wyyldeKit();
    } catch (err) {
      result = {
        channel,
        status: "error",
        error: err instanceof Error ? err.message : String(err),
      };
    }
    results.push(result);

    const { error } = await supabase.from("event_publications").upsert(
      {
        event_id: ev.id,
        channel,
        status: result.status,
        external_id: result.external_id ?? null,
        external_url: result.external_url ?? null,
        error: result.error ?? null,
        published_at: result.status === "published" ? new Date().toISOString() : null,
      },
      { onConflict: "event_id,channel" },
    );
    if (error) console.error("[social] enregistrement impossible:", error.message);
  }
  return results;
}
