// Top-level dispatch for a Google Play Real-Time Developer Notification.
//
// RTDN payload (already base64-decoded by routes/integrations/google-play.ts):
//   {
//     version, packageName, eventTimeMillis,
//     subscriptionNotification?: { version, notificationType, purchaseToken, subscriptionId },
//     oneTimeProductNotification?: { ... },
//     voidedPurchaseNotification?: { purchaseToken, orderId, productType, refundType },
//     testNotification?: { version }
//   }

import logger from '../../../libs/logger';
import { GooglePlayClient } from '../client';
import { GooglePlaySubscriptionNotification, handleGooglePlaySubscriptionEvent } from './subscription';
import { GooglePlayVoidedPurchaseNotification, handleGooglePlayVoidedPurchase } from './voided';

export type GooglePlayRtdnPayload = {
  version: string;
  packageName: string;
  eventTimeMillis?: string;
  subscriptionNotification?: GooglePlaySubscriptionNotification;
  oneTimeProductNotification?: {
    version: string;
    notificationType: number;
    purchaseToken: string;
    sku: string;
  };
  voidedPurchaseNotification?: GooglePlayVoidedPurchaseNotification;
  testNotification?: {
    version: string;
  };
};

export default async function handleGooglePlayEvent(
  payload: GooglePlayRtdnPayload,
  client: GooglePlayClient
): Promise<void> {
  if (payload.testNotification) {
    logger.info('google_play test notification received', { packageName: payload.packageName });
    return;
  }

  if (payload.subscriptionNotification) {
    await handleGooglePlaySubscriptionEvent({
      packageName: payload.packageName,
      client,
      notification: payload.subscriptionNotification,
    });
    return;
  }

  if (payload.voidedPurchaseNotification) {
    await handleGooglePlayVoidedPurchase({
      packageName: payload.packageName,
      notification: payload.voidedPurchaseNotification,
    });
    return;
  }

  if (payload.oneTimeProductNotification) {
    logger.info('google_play one-time-product notification — not handled in A2 (subscriptions only)', {
      packageName: payload.packageName,
      sku: payload.oneTimeProductNotification.sku,
    });
    return;
  }

  logger.warn('google_play notification with no recognized inner payload', { payload });
}
