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

const DEFAULT_TIME_SHEET_WEBHOOK_URL =
  "https://agenteit.digitalcompass.agency/webhook/tablero-cdc-sync-registro-horas";

export type TimeSheetSyncResult = {
  ok: boolean;
  message?: string;
  projectId?: string;
  syncedEntries?: number;
  clearedEntries?: number;
};

function getWebhookUrl() {
  return (
    String(import.meta.env.VITE_TIME_SHEET_WEBHOOK_URL || "").trim() ||
    DEFAULT_TIME_SHEET_WEBHOOK_URL
  );
}

async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs = 20_000) {
  const controller = new AbortController();
  const timeout = window.setTimeout(() => controller.abort(), timeoutMs);

  try {
    return await fetch(url, { ...init, signal: controller.signal });
  } finally {
    window.clearTimeout(timeout);
  }
}

function wait(ms: number) {
  return new Promise((resolve) => window.setTimeout(resolve, ms));
}

export async function syncProjectTimeToSheet(
  projectId: string,
): Promise<TimeSheetSyncResult> {
  const cleanProjectId = String(projectId || "").trim();
  if (!cleanProjectId) throw new Error("No se encontró el proyecto para sincronizar las horas.");

  const {
    data: { session },
    error: sessionError,
  } = await supabase.auth.getSession();

  if (sessionError) throw sessionError;
  if (!session?.access_token) {
    throw new Error("No se encontró una sesión activa para sincronizar el registro de horas.");
  }

  let lastError: Error | null = null;

  for (let attempt = 1; attempt <= 3; attempt += 1) {
    try {
      const response = await fetchWithTimeout(getWebhookUrl(), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "sync_project",
          project_id: cleanProjectId,
          access_token: session.access_token,
          source: "tablero-cdc-time",
        }),
      });

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

      if (text) {
        try {
          payload = JSON.parse(text) as TimeSheetSyncResult;
        } catch {
          payload = null;
        }
      }

      if (!response.ok || payload?.ok === false) {
        throw new Error(payload?.message || text || `Error ${response.status} al sincronizar Excel.`);
      }

      return payload || { ok: true, projectId: cleanProjectId };
    } catch (error) {
      lastError = error instanceof Error ? error : new Error(String(error || "Error de sincronización"));
      if (attempt < 3) await wait(attempt * 1_200);
    }
  }

  throw lastError || new Error("No se pudo sincronizar el registro de horas con Excel.");
}
