// Google Play integration startup checks.
//
// Unlike Stripe (we register webhook URL with Stripe at startup), Google Play's
// Real-Time Developer Notifications is configured **server-side in Google Cloud
// Pub/Sub + Play Console**, not via API call. This file just sanity-checks the
// PaymentMethod settings on app start and surfaces clear errors early.

import logger from '../../libs/logger';
import { PaymentMethod } from '../../store/models';

export async function ensureGooglePlayConfigured(): Promise<void> {
  const methods = await PaymentMethod.findAll({ where: { type: 'google_play' } });
  if (methods.length === 0) {
    return;
  }

  for (const method of methods) {
    const settings = PaymentMethod.decryptSettings(method.settings);
    const cfg = settings.google_play;
    if (!cfg) {
      logger.warn('google_play PaymentMethod missing settings', { id: method.id });
      // eslint-disable-next-line no-continue
      continue;
    }
    if (!cfg.package_name) {
      logger.warn('google_play PaymentMethod missing package_name', { id: method.id });
    }
    if (!cfg.service_account_json) {
      logger.warn('google_play PaymentMethod missing service_account_json', { id: method.id });
    } else {
      try {
        JSON.parse(cfg.service_account_json);
      } catch (err) {
        logger.error('google_play service_account_json is not valid JSON', { id: method.id });
      }
    }
    if (!cfg.pubsub_topic_name) {
      logger.warn('google_play PaymentMethod missing pubsub_topic_name', { id: method.id });
    }
  }

  logger.info('google_play PaymentMethod config checked', { count: methods.length });
}
