#!/usr/bin/env tsx
/* eslint-disable no-console */
//
// Seed a `google_play` PaymentMethod from a service account JSON file.
//
// Usage:
//   GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_PATH=/path/to/sa.json \
//   GOOGLE_PLAY_PACKAGE_NAME=io.arcblock.aistro \
//   tsx scripts/seed-google-play.ts
//
// Optional:
//   PAYMENT_METHOD_ID            existing id to update; otherwise a new one is created
//   PAYMENT_METHOD_LIVEMODE      "true" (default) | "false"
//
// The JSON contents are stored encrypted via PaymentMethod.encryptSettings.

import 'dotenv-flow/config';
import { readFileSync } from 'fs';

import { PaymentMethod } from '../api/src/store/models';
import { sequelize } from '../api/src/store/sequelize';
import migrate from '../api/src/store/migrate';
import { initialize } from '../api/src/store/models';

async function main(): Promise<void> {
  const jsonPath = process.env.GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_PATH;
  const packageName = process.env.GOOGLE_PLAY_PACKAGE_NAME;
  if (!jsonPath || !packageName) {
    console.error('Missing GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_PATH or GOOGLE_PLAY_PACKAGE_NAME');
    process.exit(1);
  }
  const livemode = process.env.PAYMENT_METHOD_LIVEMODE !== 'false';
  const existingId = process.env.PAYMENT_METHOD_ID;

  const raw = readFileSync(jsonPath, 'utf8');
  // Validate JSON shape early
  const parsed = JSON.parse(raw);
  if (!parsed.client_email || !parsed.private_key) {
    throw new Error('service account JSON missing client_email or private_key');
  }

  initialize(sequelize);
  await migrate();

  const settings = PaymentMethod.encryptSettings({
    google_play: {
      package_name: packageName,
      service_account_json: raw,
      pubsub_topic_name: '',
    },
  });

  if (existingId) {
    const method = await PaymentMethod.findByPk(existingId);
    if (!method) throw new Error(`PaymentMethod ${existingId} not found`);
    await method.update({ settings, active: true, livemode });
    console.log('updated PaymentMethod', method.id);
  } else {
    const method = await PaymentMethod.create({
      type: 'google_play',
      name: `Google Play (${packageName})`,
      description: 'In-App Billing via Google Play Console',
      logo: '',
      active: true,
      livemode,
      confirmation: { type: 'callback' },
      settings,
      features: { recurring: true, refund: true, dispute: false },
    } as any);
    console.log('created PaymentMethod', method.id, `client_email=${parsed.client_email}`);
  }

  await sequelize.close();
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
