/**
 * Google Consent Mode v2 integration helper.
 *
 * Phase 4: extracted from ConsentManager.ts. Updates gtag() with the
 * current consent category state whenever consent changes.
 */

import type { ConsentState } from '../types';

/**
 * Update Google Consent Mode v2 based on the current consent categories.
 * No-op when running outside the browser or when gtag is not loaded.
 * Returns true if the gtag update was actually applied.
 */
export function updateGoogleConsentMode(consent: ConsentState | null): boolean {
  if (typeof window === 'undefined' || !consent) {
    return false;
  }

  const gtag = (window as unknown as { gtag?: (...args: unknown[]) => void }).gtag;
  if (typeof gtag !== 'function') {
    return false;
  }

  const { categories } = consent;

  gtag('consent', 'update', {
    ad_storage: categories.marketing ? 'granted' : 'denied',
    ad_user_data: categories.marketing ? 'granted' : 'denied',
    ad_personalization: categories.marketing ? 'granted' : 'denied',
    analytics_storage: categories.analytics ? 'granted' : 'denied',
    functionality_storage: categories.functional ? 'granted' : 'denied',
    personalization_storage: categories.functional ? 'granted' : 'denied',
    security_storage: 'granted',
  });

  return true;
}
