/* eslint-disable @typescript-eslint/no-unused-vars */
// run sdk test: # pnpm run sdk-test

/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-console */
const { spawn } = require('child_process');
const payment = require('../../../packages/client/lib').default;

function getAppId() {
  const args = process.argv.slice(2);
  let appId = '';

  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--app-id' && i + 1 < args.length) {
      appId = args[i + 1];
      break;
    }
  }

  if (!appId) {
    appId =
      process.env.BLOCKLET_DEV_APP_DID?.split(':').pop() ||
      process.env.BLOCKLET_APP_ID ||
      'zNKuN3XwXN7xq2NsJQjjfwujyqCxx26DhwgV';
  }

  return appId;
}

const checkoutModule = {
  // 订阅级别管理通知
  async createWithNotification() {
    const checkoutSession = await payment.checkout.sessions.create({
      mode: 'subscription',
      line_items: [{ price_id: 'price_fQFIS12yi0JR3KePLmitjrhA', quantity: 1 }],
      subscription_data: {
        notification_settings: {
          self_handle: true,
          include_events: ['customer.subscription.started'],
        },
        no_stake: true,
      },
    });
    console.log('createWithNotification', checkoutSession);
    return checkoutSession;
  },

  // 批量订阅 + 免质押
  async createBatchSubscription() {
    const checkoutSession = await payment.checkout.sessions.create({
      mode: 'subscription',
      line_items: [
        {
          price_id: 'price_fQFIS12yi0JR3KePLmitjrhA',
          quantity: 1,
          subscription_data: {
            metadata: { test: 'test price_fQFIS12yi0JR3KePLmitjrhA' },
          },
        },
        {
          price_id: 'price_PXyI9Duz99eqty1AqbaEc73u',
          quantity: 1,
          subscription_data: {
            metadata: { test: 'test price_PXyI9Duz99eqty1AqbaEc73u' },
          },
        },
      ],
      enable_subscription_grouping: true,
      subscription_data: {
        no_stake: true,
      },
    });
    console.log('createBatchSubscription', checkoutSession);
    return checkoutSession;
  },

  // 批量订阅 + 免质押 + 自定义表单规则
  async createBatchSubscriptionWithCustomField() {
    const checkoutSession = await payment.checkout.sessions.create({
      mode: 'subscription',
      line_items: [
        {
          price_id: 'price_fQFIS12yi0JR3KePLmitjrhA',
          quantity: 1,
          subscription_data: {
            metadata: { test: 'test price_fQFIS12yi0JR3KePLmitjrhA' },
          },
        },
        {
          price_id: 'price_PXyI9Duz99eqty1AqbaEc73u',
          quantity: 1,
          subscription_data: {
            metadata: { test: 'test price_PXyI9Duz99eqty1AqbaEc73u' },
          },
        },
      ],
      enable_subscription_grouping: true,
      subscription_data: {
        no_stake: true,
      },
      phone_number_collection: {
        enabled: true,
      },
      billing_address_collection: 'required',
      metadata: {
        page_info: {
          form_purpose_description: {
            en: 'Information collected helps us process your payment and deliver our services.',
            zh: '收集的信息帮助我们处理您的付款并提供服务。',
          },
          field_validation: {
            customer_name: {
              pattern: '^[a-zA-Z\\s]{2,50}$',
              pattern_message: {
                en: 'Name should only contain 2-50 letters and spaces',
                zh: '姓名应只包含2-50个字母和空格',
              },
            },
            customer_email: {
              pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',
              pattern_message: {
                en: 'Please enter a valid email address',
                zh: '请输入有效的电子邮件地址',
              },
            },
            'billing_address.line1': {
              pattern: '^.{5,100}$',
              pattern_message: {
                en: 'Address should be 5-100 characters',
                zh: '地址应为5-100个字符',
              },
            },
          },
        },
      },
    });
    console.log('createBatchSubscriptionWithCustomField', checkoutSession);
    return checkoutSession;
  },

  // 批量订阅 + 试用 + 免质押
  async createWithTrial() {
    const checkoutSession = await payment.checkout.sessions.create({
      mode: 'subscription',
      line_items: [
        { price_id: 'price_dsjm7m1qzxEg370uLAjma4zS', quantity: 2 },
        { price_id: 'price_n9xjC3M2cILR3iWez7ToMRjd', quantity: 1 },
        { price_id: 'price_6P2bJXtWx8Awk65NC4f1PAsf', quantity: 1 },
      ],
      enable_subscription_grouping: true,
      subscription_data: {
        no_stake: true,
      },
    });
    console.log('createWithTrial', checkoutSession);
    return checkoutSession;
  },

  // 创建通知设置
  async createNotificationSetting() {
    const setting = await payment.settings.create({
      type: 'notification',
      mountLocation: 'core.sdk.test',
      description: 'test',
      settings: {
        self_handle: true,
        include_events: ['customer.subscription.started'],
      },
    });
    console.log('createNotificationSetting', setting);
    return setting;
  },

  // 应用级别管理通知
  async createCheckoutWithSettingId() {
    // 先创建设置
    const NOTIFICATION_MOUNT_LOCATION = 'core.sdk.test';
    const setting = await payment.settings.create({
      type: 'notification',
      mountLocation: NOTIFICATION_MOUNT_LOCATION,
      description: 'test',
      settings: {
        self_handle: true,
        include_events: ['customer.subscription.started'],
      },
    });
    console.log('createNotificationSetting', setting);
    // 使用设置ID创建结账会话
    const checkoutSession = await payment.checkout.sessions.create({
      mode: 'subscription',
      line_items: [{ price_id: 'price_fQFIS12yi0JR3KePLmitjrhA', quantity: 1 }],
      metadata: {
        setting_id: NOTIFICATION_MOUNT_LOCATION, // 也可以是 setting.id
      },
    });
    console.log('createCheckoutWithSettingId', checkoutSession);
    return { setting, checkoutSession };
  },

  async createCheckoutWithServiceAction() {
    const checkoutSession = await payment.checkout.sessions.create({
      mode: 'subscription',
      line_items: [{ price_id: 'price_fQFIS12yi0JR3KePLmitjrhA', quantity: 1 }],
      subscription_data: {
        service_actions: [
          {
            text: {
              zh: '全链接测试',
              en: 'Full Link Test',
            },
            link: 'https://baidu.com',
          },
          {
            text: {
              zh: '相对路径访问',
              en: 'Relative Path Access',
            },
            link: '/.well-known/service/user/notifications',
          },
        ],
      },
    });
    console.log('createCheckoutWithServiceAction', checkoutSession);
  },
};

const paymentModule = {
  // 获取支付意图
  async retrievePaymentIntent() {
    const paymentIntent = await payment.paymentIntents.retrieve('pi_ybTOCWweEnb9grWZsTH7MCVi');
    console.log('retrievePaymentIntent', paymentIntent);
    return paymentIntent;
  },

  // === 退款相关测试 ===

  // 创建退款
  async createRefund() {
    const paymentIntentId = 'pi_ybTOCWweEnb9grWZsTH7MCVi';

    const refundResult = await payment.paymentIntents.refund(paymentIntentId, {
      amount: '0.001',
      reason: 'requested_by_customer',
      description: 'Refund Test',
    });
    console.log('createRefund', refundResult);
    return refundResult;
  },

  // 获取退款详情
  async retrieveRefund() {
    const refund = await payment.refunds.retrieve('re_loHv143R78cSe38uGjxRBsfv');
    console.log('retrieveRefund', refund);
    return refund;
  },

  // 获取退款列表
  async listRefunds() {
    const paymentIntentId = 'pi_ybTOCWweEnb9grWZsTH7MCVi';
    const paymentIntent = await payment.paymentIntents.retrieve(paymentIntentId);

    const refunds = await payment.refunds.list({
      invoice_id: paymentIntent.invoice_id,
    });
    console.log('listRefunds', refunds);
    return refunds;
  },

  // 创建自定义退款
  async createCustomRefund() {
    const paymentIntentId = 'pi_ybTOCWweEnb9grWZsTH7MCVi';
    const paymentIntent = await payment.paymentIntents.retrieve(paymentIntentId);

    const refundData = {
      amount: '0.001',
      reason: 'requested_by_admin',
      description: 'Custom Refund Test',
      invoice_id: paymentIntent.invoice_id,
      payment_intent_id: paymentIntent.id,
      currency_id: paymentIntent.currency_id,
      payment_method_id: paymentIntent.payment_method_id,
      customer_id: paymentIntent.customer_id,
    };

    const customRefund = await payment.refunds.create(refundData);
    console.log('createCustomRefund', customRefund);
    return customRefund;
  },

  // 完整支付和退款流程
  async paymentAndRefundFlow() {
    // 注意：测试中使用已有的支付意图，实际应用中应先创建支付意图
    const paymentIntentId = 'pi_ybTOCWweEnb9grWZsTH7MCVi';
    const paymentIntent = await payment.paymentIntents.retrieve(paymentIntentId);

    const partialRefund = await payment.paymentIntents.refund(paymentIntentId, {
      amount: '0.0005', // 部分金额
      reason: 'requested_by_customer',
      description: 'Partial Refund Test',
    });

    const refunds = await payment.refunds.list({
      invoice_id: paymentIntent.invoice_id,
    });

    console.log('paymentAndRefundFlow', {
      paymentIntent,
      partialRefund,
      refundsList: refunds,
    });
    return {
      paymentIntent,
      partialRefund,
      refundsList: refunds,
    };
  },
};

const productModule = {
  // 创建单个产品
  async createProduct() {
    const product = await payment.products.create({
      name: 'Test SDK product',
      description: 'test',
    });
    console.log('createProduct', product);
    return product;
  },

  // === 价格相关测试 ===

  // 方式1：创建产品时一并创建价格
  async createProductWithPrice() {
    const product = await payment.products.create({
      name: 'Test One-time Price Product',
      description: 'Product for one-time price test',
      type: 'good',
      prices: [
        {
          type: 'one_time',
          unit_amount: '1',
          currency_id: 'pc_9l5sh8bcjbLU',
          lookup_key: 'test_one_time_price',
        },
      ],
    });
    console.log('createProductWithPrice', product);
    return product;
  },

  // 方式2：先创建产品，再创建价格
  async createOneTimePrice() {
    const product = await payment.products.create({
      name: 'Test Separate Price Product',
      description: 'Product for separate price creation test',
    });

    const price = await payment.prices.create({
      product_id: product.id,
      type: 'one_time',
      unit_amount: '1',
      currency_id: 'pc_9l5sh8bcjbLU',
    });
    console.log('createOneTimePrice', { product, price });
    return { product, price };
  },

  // 创建循环订阅价格
  async createRecurringPrice() {
    const productId = 'prod_Acj9sSjFaABVQm'; // 使用已存在的产品ID

    const price = await payment.prices.create({
      locked: false,
      model: 'standard',
      billing_scheme: '',
      currency_id: 'pc_aW2zy2y8yoi7',
      nickname: '',
      type: 'recurring',
      unit_amount: '0.001',
      lookup_key: '',
      recurring: {
        interval_config: 'month_1',
        interval: 'month',
        interval_count: 1,
        usage_type: 'licensed',
        aggregate_usage: 'sum',
      },
      transform_quantity: { divide_by: 1, round: 'up' },
      tiers: [],
      metadata: [],
      custom_unit_amount: null,
      currency_options: [],
      tiers_mode: null,
      quantity_available: 10,
      quantity_limit_per_checkout: '2',
      product_id: productId,
    });
    console.log('createRecurringPrice', price);
    return price;
  },

  // 价格库存管理
  async updateInventory() {
    const inventoryPrice = await payment.prices.inventory('price_xUd1QXTwhoIdOfHa9WT6MdBe', {
      quantity: 1,
      action: 'decrement',
    });
    console.log('updateInventory', inventoryPrice);
    return inventoryPrice;
  },

  // 完整流程：展示两种创建方式
  async createProductWithPrices() {
    // 方式1：内联价格
    const productWithInlinePrices = await payment.products.create({
      name: 'Product with Inline Prices',
      description: 'Product with prices defined inline',
      prices: [
        {
          type: 'one_time',
          unit_amount: '15',
          currency_id: 'pc_9l5sh8bcjbLU',
        },
        {
          type: 'recurring',
          unit_amount: '7.5',
          currency_id: 'pc_aW2zy2y8yoi7',
          recurring: {
            interval_config: 'month_1',
            interval: 'month',
            interval_count: 1,
            usage_type: 'licensed',
          },
        },
      ],
    });

    // 方式2：分步创建
    const product = await payment.products.create({
      name: 'Product with Separate Prices',
      description: 'Product with separately defined prices',
    });

    const oneTimePrice = await payment.prices.create({
      product_id: product.id,
      type: 'one_time',
      unit_amount: '10',
      currency_id: 'pc_9l5sh8bcjbLU',
    });

    const subscriptionPrice = await payment.prices.create({
      product_id: product.id,
      type: 'recurring',
      unit_amount: '5',
      currency_id: 'pc_aW2zy2y8yoi7',
      recurring: {
        interval_config: 'month_1',
        interval: 'month',
        interval_count: 1,
        usage_type: 'licensed',
      },
    });
    console.log('createProductWithPrices', {
      inlineMethod: productWithInlinePrices,
      separateMethod: {
        product,
        prices: {
          oneTime: oneTimePrice,
          subscription: subscriptionPrice,
        },
      },
    });
    return {
      inlineMethod: productWithInlinePrices,
      separateMethod: {
        product,
        prices: {
          oneTime: oneTimePrice,
          subscription: subscriptionPrice,
        },
      },
    };
  },
};

const subscriptionModule = {
  // 获取所有订阅
  async listSubscriptions() {
    const subscriptions = await payment.subscriptions.list({
      order: 'updated_at:ASC',
      // 支持Sequelize排序格式
      // order: [
      //   ['status', 'DESC'],
      //   ['updated_at', 'ASC'],
      // ],
      activeFirst: true,
    });
    console.log('listSubscriptions', subscriptions);
    return subscriptions;
  },

  // 上报用量
  async createUsageRecord() {
    const record = {
      subscription_item_id: 'si_Tq4c2KsC40uPq7',
      quantity: 1,
      action: 'increment',
      livemode: false,
      timestamp: Math.floor(Date.now() / 1000),
    };

    const result = await payment.subscriptionItems.createUsageRecord(record);
    console.log('createUsageRecord', result);
    return result;
  },

  // 并发上报
  async createBatchUsageRecords() {
    const records = [
      {
        subscription_item_id: 'si_Tq4c2KsC40uPq7',
        quantity: 1,
        action: 'increment',
        livemode: false,
        timestamp: Math.floor(Date.now() / 1000),
      },
      {
        subscription_item_id: 'si_Tq4c2KsC40uPq7',
        quantity: 2,
        action: 'increment',
        livemode: false,
        timestamp: Math.floor(Date.now() / 1000),
      },
    ];

    const results = await Promise.allSettled(
      records.map((record) => payment.subscriptionItems.createUsageRecord(record))
    );
    console.log('createBatchUsageRecords', results);
    return results;
  },

  // 返回质押
  async returnStake() {
    const result = await payment.subscriptions.returnStake('sub_pWYXj2fale49qeFfEpunTmZq');
    console.log('returnStake', result);
    return result;
  },
};

const meterModule = {
  async createMeter() {
    const meter = await payment.meters.create({
      name: 'API Calls',
      event_name: 'api_calls',
      aggregation_method: 'sum',
      unit: 'Token',
      description: 'Track API usage',
      component_did: 'zNKtcX5QyTxfM51osn5W8GMWvzabBREW2abA',
      created_via: 'api',
    });
    console.log('Created meter:', meter);
    return meter;
  },

  // 创建基于 Meter 的订阅产品和价格
  async createMeteredSubscription() {
    let meter;
    try {
      meter = await payment.meters.retrieve('api_calls');
      if (!meter) {
        meter = await this.createMeter();
      }
    } catch (error) {
      meter = await this.createMeter();
    }

    // 创建订阅产品
    const subscriptionProduct = await payment.products.create({
      name: 'API Call Service',
      description: 'API Call Service',
    });

    // 创建基于 meter 的订阅价格
    const subscriptionPrice = await payment.prices.create({
      product_id: subscriptionProduct.id,
      currency_id: meter.currency_id,
      unit_amount: '1',
      type: 'recurring',
      recurring: {
        interval: 'month',
        interval_count: 1,
        usage_type: 'metered',
        meter_id: meter.id,
        aggregate_usage: 'sum',
      },
    });

    console.log('subscriptionPrice', subscriptionPrice);
    // 创建 checkout session
    const subscriptionCheckout = await payment.checkout.sessions.create({
      success_url: 'https://audiobook.com/success?session_id={CHECKOUT_SESSION_ID}',
      cancel_url: 'https://audiobook.com/cancel',
      mode: 'subscription',
      line_items: [
        {
          price_id: subscriptionPrice.id,
          quantity: 1,
        },
      ],
    });

    console.log('Metered subscription checkout:', subscriptionCheckout);
    return { meter, subscriptionProduct, subscriptionPrice, subscriptionCheckout };
  },
};

// 新增 Credit 相关模块
const creditModule = {
  // 创建 Credit 产品
  async createCreditProduct(meter) {
    const creditProduct = await payment.products.create({
      name: 'API Calls Credit',
      description: 'API Call Credit, we can ...',
      type: 'credit',
      prices: [
        {
          type: 'one_time',
          unit_amount: '0.01',
          currency_id: 'pc_ByBkyhRQmedm',
          currency_options: [
            { currency_id: 'pc_ByBkyhRQmedm', unit_amount: '0.01' },
            { currency_id: 'pc_Dp4lY5ejkALH', unit_amount: '0.01' },
          ],
          lookup_key: 'api_call_credit_per_unit',
          nickname: 'Per Unit Credit For API Call',
          metadata: {
            credit_config: {
              priority: 50,
              valid_duration_value: 0,
              valid_duration_unit: 'days',
              currency_id: meter.currency_id,
              credit_amount: '1',
            },
            meter_id: meter.id,
          },
        },
        {
          type: 'one_time',
          unit_amount: '8',
          currency_id: 'pc_ByBkyhRQmedm',
          lookup_key: 'api_calls_1000_pack',
          nickname: '1000 Credits Pack For API Call',
          currency_options: [
            { currency_id: 'pc_ByBkyhRQmedm', unit_amount: '8' },
            { currency_id: 'pc_Dp4lY5ejkALH', unit_amount: '8' },
          ],
          metadata: {
            credit_config: {
              priority: 50,
              valid_duration_value: 0,
              valid_duration_unit: 'days',
              currency_id: meter.currency_id,
              credit_amount: '1000',
            },
            meter_id: meter.id,
          },
        },
      ],
    });
    console.log('Created credit product:', creditProduct.id);
    console.log(
      'Available prices:',
      creditProduct.prices.map((p) => p.lookup_key)
    );
    return creditProduct;
  },

  // 创建支付链接
  async createPaymentLinks() {
    const perUnitPrice = await payment.prices.retrieve('api_call_credit_per_unit');
    console.log('perUnitPrice', perUnitPrice);
    // 1. 按分钟购买
    const flexiblePaymentLink = await payment.paymentLinks.create({
      name: 'Per Unit Credit Link',
      currency_id: perUnitPrice.currency_id,
      line_items: [
        {
          price_id: perUnitPrice.id,
          quantity: 100,
          adjustable_quantity: {
            enabled: true,
            minimum: 10,
            maximum: 10000,
          },
        },
      ],
      metadata: {
        credit_purchase: 'true',
      },
    });

    const packPrice = await payment.prices.retrieve('api_calls_1000_pack');
    console.log('packPrice', packPrice);
    // 2. 固定套餐包
    const packagePaymentLink = await payment.paymentLinks.create({
      name: 'Package Credit Link',
      currency_id: packPrice.currency_id,
      line_items: [
        {
          price_id: packPrice.id,
          quantity: 1,
        },
      ],
      metadata: {
        credit_purchase: 'true',
      },
    });

    console.log('Flexible payment link:', flexiblePaymentLink);
    console.log('Package payment link:', packagePaymentLink);
    return { flexiblePaymentLink, packagePaymentLink };
  },

  // 创建/赠送 Credit Grant
  async createCreditGrant(meter) {
    // 方式2: 通用 Credit Grant
    const universalCredit = await payment.creditGrants.create({
      customer_id: 'cus_xga1PZSmiDZfz0',
      amount: 50,
      currency_id: meter.currency_id,
      applicability_config: {
        scope: {
          price_type: 'metered',
        },
      },
      category: 'promotional',
      name: '听书时长充值',
      metadata: {
        purchase_source: 'mobile_app',
      },
    });
    console.log('Universal credit grant:', universalCredit);
    return { universalCredit };
  },

  // 上报 Credit 消耗用量
  async reportUsage(customerId, minutes, sessionContext) {
    const creditBalance = await payment.creditGrants.summary({
      customer_id: customerId,
    });
    console.log('creditBalance', creditBalance);
    const meterEvent = await payment.meterEvents.create({
      event_name: 'api_calls',
      timestamp: Math.floor(Date.now() / 1000),
      payload: {
        customer_id: customerId,
        value: String(minutes),
        subscription_id: sessionContext.subscriptionId || undefined,
      },
      identifier: `${customerId}_${sessionContext.sessionId}_${Date.now()}`,
      metadata: {
        session_id: sessionContext.sessionId,
      },
    });

    return {
      event_id: meterEvent.id,
      identifier: meterEvent.identifier,
      timestamp: meterEvent.timestamp,
    };
  },
};

const testModules = {
  checkout: checkoutModule,
  payment: paymentModule,
  product: productModule,
  subscription: subscriptionModule,
  meter: meterModule,
  credit: creditModule,
};

// 测试入口
async function runTest() {
  payment.environments.setTestMode(true);
  const { meter } = await testModules.meter.createMeteredSubscription();
  // await testModules.credit.createCreditProduct(meter);
  // await testModules.credit.createPaymentLinks();
  // await testModules.credit.createCreditGrant(meter);
  await testModules.credit.reportUsage('cus_xga1PZSmiDZfz0', 2, {
    sessionId: 'session_123',
  });
}

async function main() {
  if (process.env.BLOCKLET_APP_ID) {
    await runTest();
    process.exit(0);
  }

  const appId = getAppId();
  const args = process.argv.slice(2).filter((arg) => arg !== '--app-id' && arg !== appId);

  console.log(`Running with blocklet exec, app-id: ${appId}`);

  const child = spawn('blocklet', ['exec', '/scripts/sdk.js', '--app-id', appId, ...args], {
    stdio: 'inherit',
  });

  child.on('exit', (code) => {
    process.exit(code || 0);
  });
}

if (require.main === module) {
  main().catch((error) => {
    console.error('Error:', error);
    process.exit(1);
  });
}
