import db from '../../config/database';
import { logger } from '../../utils/logger';

/**
 * [BIZ_FIN_195] 基于实时毛利的动态运费模板建议 (Shipping Cost)
 * @description 优化包邮门槛，动态调整运费模板。
 */
export class DynamicShippingService {
  private static readonly TEMPLATE_TABLE = 'cf_dynamic_shipping_templates';

  /**
   * 生成运费模板建议
   */
  static async suggestShippingThreshold(tenantId: string) {
    logger.info(`[DynamicShipping] Suggesting threshold for tenant: ${tenantId}`);

    // 1. 获取过去 30 天的订单平均净利和运费成本
    const stats = await db('cf_recon_records')
      .where({ tenantId })
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(
        db.raw('AVG(netProfit) as avgProfit'),
        db.raw('AVG(logisticsFee) as avgLogisticsFee'),
        db.raw('AVG(platformAmount) as avgOrderValue')
      );

    const avgProfit = Number(stats[0].avgProfit || 0);
    const avgLogisticsFee = Number(stats[0].avgLogisticsFee || 0);
    const avgOrderValue = Number(stats[0].avgOrderValue || 0);

    // 2. 建议包邮门槛 (确保包邮后净利仍 > 15%)
    // 假设门槛 = 运费成本 / 目标毛利率
    const targetMargin = 0.15;
    const suggestedThreshold = avgLogisticsFee / targetMargin;

    let suggestion = 'MAINTAIN_CURRENT';
    let recommendation = `Current average order value ($${avgOrderValue.toFixed(2)}) is healthy.`;

    if (suggestedThreshold > avgOrderValue * 1.2) {
      suggestion = 'INCREASE_THRESHOLD';
      recommendation = `Increase free shipping threshold to $${suggestedThreshold.toFixed(0)} to protect margin.`;
    } else if (suggestedThreshold < avgOrderValue * 0.8) {
      suggestion = 'DECREASE_THRESHOLD';
      recommendation = `Consider lowering threshold to $${suggestedThreshold.toFixed(0)} to boost conversion.`;
    }

    const template = {
      id: `ST-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      avgProfit: Number(avgProfit.toFixed(2)),
      avgLogisticsFee: Number(avgLogisticsFee.toFixed(2)),
      suggestedThreshold: Number(suggestedThreshold.toFixed(2)),
      suggestion,
      recommendation,
      created_at: new Date()
    };

    // 3. 存储建议记录
    await db(this.TEMPLATE_TABLE)
      .insert(template)
      .onConflict(['id'])
      .merge();

    return template;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TEMPLATE_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TEMPLATE_TABLE} table...`);
      await db.schema.createTable(this.TEMPLATE_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.decimal('avgProfit', 15, 2);
        table.decimal('avgLogisticsFee', 15, 2);
        table.decimal('suggestedThreshold', 15, 2);
        table.string('suggestion', 20); // E.g., INCREASE_THRESHOLD, DECREASE_THRESHOLD, MAINTAIN_CURRENT
        table.text('recommendation');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId']);
      });
    }
  }
}
