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

export type MembershipTier = 'BRONZE' | 'SILVER' | 'GOLD' | 'PLATINUM';

export interface CustomerLTV {
  customerDid: string;
  predictedLTV: number;
  historicalSpend: number;
  orderCount: number;
  currentTier: MembershipTier;
}

/**
 * [BIZ_MKT_60] 基于 LTV 预测的自动化会员等级晋升 (LTV Membership)
 * @description 根据 AGI 预测的 LTV，自动为高价值客户晋升等级并解锁权益。
 */
export class MembershipLTVService {
  private static readonly MEMBERSHIP_TABLE = 'cf_customer_memberships';

  /**
   * 评估并晋升会员等级
   */
  static async evaluateTier(tenantId: string, customerDid: string) {
    logger.info(`[MembershipLTV] Evaluating membership tier for customer: ${customerDid}`);

    // 1. 获取客户历史数据
    const orders = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId, customer_id: customerDid })
      .select(db.raw('SUM(total_amount) as totalSpend'), db.raw('COUNT(*) as orderCount'));

    const historicalSpend = Number(orders[0].totalSpend || 0);
    const orderCount = Number(orders[0].orderCount || 0);

    // 2. AGI 预测 LTV (简单模型：历史消费 * 1.5 + 订单数 * 10)
    const predictedLTV = (historicalSpend * 1.5) + (orderCount * 10);

    // 3. 决定新等级
    let newTier: MembershipTier = 'BRONZE';
    if (predictedLTV > 5000) newTier = 'PLATINUM';
    else if (predictedLTV > 2000) newTier = 'GOLD';
    else if (predictedLTV > 500) newTier = 'SILVER';

    // 4. 更新会员表
    const membership = {
      tenant_id: tenantId,
      customer_did: customerDid,
      historical_spend: historicalSpend,
      predicted_ltv: Number(predictedLTV.toFixed(2)),
      tier: newTier,
      updated_at: new Date()
    };

    await db(this.MEMBERSHIP_TABLE)
      .insert({ ...membership, created_at: new Date() })
      .onConflict(['tenant_id', 'customer_did'])
      .merge();

    logger.info(`[MembershipLTV] Customer ${customerDid} tier updated to ${newTier} (LTV: $${predictedLTV})`);

    return membership;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.MEMBERSHIP_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.MEMBERSHIP_TABLE} table...`);
      await db.schema.createTable(this.MEMBERSHIP_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('customer_did', 128).notNullable();
        table.decimal('historical_spend', 15, 2).defaultTo(0);
        table.decimal('predicted_ltv', 15, 2).defaultTo(0);
        table.string('tier', 32).defaultTo('BRONZE');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.timestamp('updated_at').defaultTo(db.fn.now());
        table.unique(['tenant_id', 'customer_did']);
      });
    }
  }
}
