import { decryptSecret } from "@/lib/ai/crypto";
import { createAdminClient } from "@/lib/supabase/admin";
import { getIntegrationEventLabel } from "@/lib/integrations/catalog";
import type { WebhookEventEnvelope } from "@/lib/developers/webhooks";
import type { IntegrationConnection } from "@/types";

interface TelegramCredentials {
  botToken: string;
  chatId: string;
  botUsername?: string | null;
}

function parseCredentials(secretEncrypted: string) {
  return JSON.parse(decryptSecret(secretEncrypted)) as TelegramCredentials;
}

function getPrimaryTitle(data: Record<string, unknown>) {
  for (const key of ["project", "task", "note", "event"] as const) {
    const value = data[key];
    if (value && typeof value === "object") {
      const record = value as Record<string, unknown>;
      if (typeof record.name === "string" && record.name.trim()) return record.name.trim();
      if (typeof record.title === "string" && record.title.trim()) return record.title.trim();
    }
  }

  return "Workspace update";
}

function buildTelegramText(envelope: WebhookEventEnvelope) {
  const label = getIntegrationEventLabel(envelope.type);
  const title = getPrimaryTitle(envelope.data);
  const workspaceLabel = envelope.workspace.team_id ? "Team workspace" : "Personal workspace";

  return [
    `*${label}*`,
    title,
    "",
    `${workspaceLabel} · ${new Date(envelope.created_at).toLocaleString()}`,
  ].join("\n");
}

export async function deliverTelegramIntegrationEvent(
  admin: ReturnType<typeof createAdminClient>,
  connection: IntegrationConnection & { secret_encrypted: string },
  envelope: WebhookEventEnvelope
) {
  const credentials = parseCredentials(connection.secret_encrypted);
  const payload = {
    chat_id: credentials.chatId,
    text: buildTelegramText(envelope),
    parse_mode: "Markdown",
    disable_web_page_preview: true,
  };

  let responseStatus: number | null = null;
  let responseBody: string | null = null;
  let success = false;

  try {
    const response = await fetch(
      `https://api.telegram.org/bot${credentials.botToken}/sendMessage`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "User-Agent": "Mindavio-Telegram/1.0",
        },
        body: JSON.stringify(payload),
      }
    );

    responseStatus = response.status;
    responseBody = (await response.text()).slice(0, 4000) || null;
    success = response.ok;
  } catch (error) {
    responseBody =
      error instanceof Error ? error.message.slice(0, 4000) : "Telegram delivery failed";
  }

  await admin.from("integration_deliveries").insert({
    connection_id: connection.id,
    user_id: connection.user_id,
    team_id: connection.team_id,
    provider: connection.provider,
    event_type: envelope.type,
    payload: envelope,
    response_status: responseStatus,
    response_body: responseBody,
    success,
  });

  await admin
    .from("integration_connections")
    .update({
      last_delivery_at: new Date().toISOString(),
      last_response_status: responseStatus,
      last_error: success ? null : responseBody,
    })
    .eq("id", connection.id);
}
