/**
 * Nango Server Client
 * ───────────────────
 * Wraps @nangohq/node for server-side connection management
 * and data fetching. Each brand uses its brandId as the Nango
 * connectionId so connections are 1:1 with brands.
 */

import { Nango } from "@nangohq/node";

const NANGO_SECRET_KEY = process.env.NANGO_SECRET_KEY ?? "";

function getNangoClient(): Nango | null {
  if (!NANGO_SECRET_KEY) return null;
  return new Nango({ secretKey: NANGO_SECRET_KEY });
}

export function isNangoConfigured(): boolean {
  return !!NANGO_SECRET_KEY;
}

export async function getNangoConnection(providerConfigKey: string, connectionId: string) {
  const nango = getNangoClient();
  if (!nango) return null;
  try {
    return await nango.getConnection(providerConfigKey, connectionId);
  } catch {
    return null;
  }
}

export async function listNangoConnections(connectionId?: string) {
  const nango = getNangoClient();
  if (!nango) return [];
  try {
    const result = await nango.listConnections();
    const all = result.connections ?? [];
    return connectionId ? all.filter((c) => c.connection_id === connectionId) : all;
  } catch {
    return [];
  }
}

export async function deleteNangoConnection(providerConfigKey: string, connectionId: string) {
  const nango = getNangoClient();
  if (!nango) return false;
  try {
    await nango.deleteConnection(providerConfigKey, connectionId);
    return true;
  } catch {
    return false;
  }
}

/**
 * Nango provider config keys mapped to display labels used on the
 * Integrations page. Only integrations present in this map show the
 * "Connect" button — everything else keeps "Coming Soon".
 */
export const NANGO_PROVIDERS: Record<string, string> = {
  "Google Ads": "google-ads",
  "Meta Ads": "facebook-ads",
  "HubSpot": "hubspot",
  "Salesforce": "salesforce",
  "CallRail": "callrail",
  "LinkedIn Ads": "linkedin-ads",
  "Mailchimp": "mailchimp",
  "Klaviyo": "klaviyo",
  "Shopify": "shopify",
  "TikTok Ads": "tiktok-ads",
  "Microsoft Ads": "microsoft-ads",
  "Google Business Profile": "google-business-profile",
  "Stripe": "stripe",
};
