import { supabase } from "@/lib/supabase";

export type ManagedListCategory = "client" | "brand" | "country" | "status";
export type ManagedListAction = "create" | "update" | "delete" | "refresh";

export type ManagedListMutation = {
  action: ManagedListAction;
  category?: ManagedListCategory;
  value?: string;
  previousValue?: string;
  manager?: string;
};

export type ManagedListMutationResult = {
  ok?: boolean;
  message?: string;
  action?: string;
  category?: string;
  totalRecords?: number;
};

const DEFAULT_LISTS_WEBHOOK_URL =
  "https://agenteit.digitalcompass.agency/webhook/tablero-cdc-sync-listas-admin";

function getListsWebhookUrl() {
  return import.meta.env.VITE_LISTS_WEBHOOK_URL?.trim() || DEFAULT_LISTS_WEBHOOK_URL;
}

export async function mutateManagedList(
  mutation: ManagedListMutation,
): Promise<ManagedListMutationResult> {
  const { data, error } = await supabase.auth.getSession();

  if (error || !data.session?.access_token) {
    throw new Error("No hay una sesión activa. Recarga la página e inicia sesión nuevamente.");
  }

  const controller = new AbortController();
  const timeout = window.setTimeout(() => controller.abort(), 20000);

  try {
    const response = await fetch(getListsWebhookUrl(), {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        action: mutation.action,
        category: mutation.category || "",
        value: mutation.value || "",
        previous_value: mutation.previousValue || "",
        manager: mutation.manager || "",
        source: "tablero-cdc",
        access_token: data.session.access_token,
        sent_at: new Date().toISOString(),
      }),
      signal: controller.signal,
    });

    const text = await response.text();
    let payload: ManagedListMutationResult | null = null;

    if (text) {
      try {
        payload = JSON.parse(text) as ManagedListMutationResult;
      } catch {
        payload = { message: text };
      }
    }

    if (!response.ok) {
      throw new Error(payload?.message || `${response.status} ${response.statusText}`.trim());
    }

    return payload || { ok: true };
  } catch (error) {
    if (error instanceof DOMException && error.name === "AbortError") {
      throw new Error("n8n tardó demasiado en responder. Revisa el workflow de sincronización de listas.");
    }
    throw error;
  } finally {
    window.clearTimeout(timeout);
  }
}
