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

/**
 * [BIZ_FIN_178] 租户层级 P&L 波动根因分析报告 (Tenant Profit)
 * @description 监控租户 P&L 异常波动并预警。
 */
export class TenantHealthService {
  private static readonly HEALTH_TABLE = 'cf_tenant_health_alerts';

  /**
   * 检查租户健康状况
   */
  static async checkTenantHealth(tenantId: string) {
    logger.info(`[TenantHealth] Checking profit health for tenant: ${tenantId}`);

    // 1. 获取过去 30 天的每日净利润
    const profitTrends = await db('cf_recon_records')
      .where({ tenantId })
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(
        db.raw('DATE(created_at) as date'),
        db.raw('SUM(netProfit) as dailyProfit')
      )
      .groupBy('date')
      .orderBy('date', 'desc');

    if (profitTrends.length < 2) return null;

    const latestProfit = Number(profitTrends[0].dailyProfit);
    const previousProfit = Number(profitTrends[1].dailyProfit);

    // 2. 识别异常波动 (> 50% 下降)
    const changeRatio = previousProfit !== 0 ? (latestProfit - previousProfit) / Math.abs(previousProfit) : 0;
    let status = 'HEALTHY';
    let alertMsg = 'Profit is stable';

    if (changeRatio < -0.5) {
      status = 'CRITICAL';
      alertMsg = `Profit dropped by ${(Math.abs(changeRatio) * 100).toFixed(2)}% compared to yesterday.`;
    } else if (changeRatio < -0.2) {
      status = 'WARNING';
      alertMsg = `Profit decreased by ${(Math.abs(changeRatio) * 100).toFixed(2)}%.`;
    }

    const alertRecord = {
      id: `HA-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      status,
      changeRatio: Number(changeRatio.toFixed(4)),
      latestProfit,
      previousProfit,
      alertMsg,
      created_at: new Date()
    };

    // 3. 存储报警记录
    await db(this.HEALTH_TABLE)
      .insert(alertRecord)
      .onConflict(['id'])
      .merge();

    return alertRecord;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.HEALTH_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.HEALTH_TABLE} table...`);
      await db.schema.createTable(this.HEALTH_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('status', 20); // E.g., HEALTHY, WARNING, CRITICAL
        table.decimal('changeRatio', 5, 4);
        table.decimal('latestProfit', 15, 2);
        table.decimal('previousProfit', 15, 2);
        table.text('alertMsg');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId']);
      });
    }
  }
}
