/**
 * WhatsApp Webhook Registration Service
 *
 * Registers and manages webhook subscriptions with Meta's Graph API.
 * Used by both the manual connect flow and Meta Embedded Signup OAuth flow.
 */

import { logger } from '@/lib/logger';

const META_GRAPH_API = 'https://graph.facebook.com/v19.0';

/**
 * Register our webhook URL with Meta for a WhatsApp Business Account.
 *
 * Subscribes the app to receive webhook events for the given
 * WABA. Required for receiving incoming messages and status updates.
 */
export async function registerWebhook(
  wabaId: string,
  accessToken: string,
): Promise<{ success: boolean; error?: string }> {
  try {
    const response = await fetch(
      `${META_GRAPH_API}/${wabaId}/subscribed_apps`,
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${accessToken}`,
          'Content-Type': 'application/json',
        },
      },
    );

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      const errorMessage =
        errorData?.error?.message || 'Failed to register webhook';
      logger.error('[WebhookReg] Failed to subscribe app', {
        wabaId,
        status: response.status,
        error: errorMessage,
      });
      return { success: false, error: errorMessage };
    }

    logger.info('[WebhookReg] Webhook registered successfully', { wabaId });
    return { success: true };
  } catch (error) {
    logger.error('[WebhookReg] Webhook registration error', {
      wabaId,
      error,
    });
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Webhook registration failed',
    };
  }
}
