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

export async function deliverGoogleSheetsIntegrationEvent(
  admin: ReturnType<typeof createAdminClient>,
  connection: IntegrationConnection & { secret_encrypted: string },
  envelope: WebhookEventEnvelope
) {
  const webhookUrl = decryptSecret(connection.secret_encrypted);

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

  try {
    const response = await fetch(webhookUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "User-Agent": "Mindavio-GoogleSheets/1.0",
      },
      body: JSON.stringify(envelope),
    });

    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) : "Google Sheets 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);
}
