// Top-level dispatch for an App Store Server Notification V2.
//
// Apple S2S envelope (already decoded by routes/integrations/app-store.ts):
//   {
//     notificationType: "DID_RENEW" | "EXPIRED" | ... ,
//     subtype?: "INITIAL_BUY" | "VOLUNTARY" | ...,
//     notificationUUID: "<uuid>",
//     version: "2.0",
//     signedDate: <unix ms>,
//     data: {
//       bundleId, environment,
//       signedTransactionInfo, signedRenewalInfo,
//       status (1=active, 2=expired, 3=billing-retry, 4=grace, 5=revoked)
//     }
//   }

import logger from '../../../libs/logger';
import { AppStoreClient, AppStoreNotificationPayload } from '../client';
import { handleAppStoreSubscriptionEvent } from './subscription';

export default async function handleAppStoreNotification(
  notification: AppStoreNotificationPayload,
  client: AppStoreClient
): Promise<void> {
  if (notification.notificationType === 'TEST') {
    logger.info('app_store TEST notification received', {
      notificationUUID: notification.notificationUUID,
      bundleId: notification.data.bundleId,
    });
    return;
  }

  // Every actionable notification carries the inner transaction JWS — decode it
  // here so the state machine can be tested with a pre-decoded payload.
  if (!notification.data.signedTransactionInfo) {
    logger.warn('app_store notification has no signedTransactionInfo — nothing to dispatch', {
      notificationType: notification.notificationType,
      notificationUUID: notification.notificationUUID,
    });
    return;
  }

  const transaction = await client.verifyJwsTransaction(notification.data.signedTransactionInfo);

  await handleAppStoreSubscriptionEvent({ notification, transaction });
}
