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

/**
 * [BIZ_FIN_186] 库存周转率异常导致的资金占用预警 (Turnover)
 * @description 监控库存周转率，预警由于库存积压导致的资金占用。
 */
export class TurnoverWatchdog {
  private static readonly WATCHDOG_TABLE = 'cf_turnover_alerts';

  /**
   * 检查库存周转率
   */
  static async checkInventoryTurnover(tenantId: string) {
    logger.info(`[TurnoverWatchdog] Checking inventory turnover for tenant: ${tenantId}`);

    // 1. 获取过去 30 天的销售成本 (COGS) 和平均库存价值
    const sales = await db('cf_recon_records')
      .where({ tenantId })
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(db.raw('SUM(platformAmount - netProfit) as totalCOGS')); // 简化 COGS = 收入 - 净利

    const totalCOGS = Number(sales[0].totalCOGS || 0);

    const inventory = await db('cf_inventory')
      .where({ tenant_id: tenantId })
      .select(db.raw('SUM(quantity * cost_price) as totalValue'));

    const totalValue = Number(inventory[0].totalValue || 0);

    if (totalValue === 0) return null;

    // 2. 计算周转率 (月度)
    // 周转率 = COGS / 平均库存
    const monthlyTurnover = totalCOGS / totalValue;
    const daysToTurnover = monthlyTurnover > 0 ? 30 / monthlyTurnover : 365; // 天数

    // 3. 预警级别
    let riskLevel = 'LOW';
    let alertMsg = 'Healthy inventory turnover';

    if (daysToTurnover > 90) {
      riskLevel = 'CRITICAL';
      alertMsg = `Inventory is sitting for ${daysToTurnover.toFixed(0)} days. Capital is being tied up.`;
    } else if (daysToTurnover > 60) {
      riskLevel = 'WARNING';
      alertMsg = `Turnover is slowing down (${daysToTurnover.toFixed(0)} days). Monitor closely.`;
    }

    const alertRecord = {
      id: `TO-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      monthlyTurnover: Number(monthlyTurnover.toFixed(4)),
      daysToTurnover: Number(daysToTurnover.toFixed(0)),
      totalCOGS: Number(totalCOGS.toFixed(2)),
      totalValue: Number(totalValue.toFixed(2)),
      riskLevel,
      alertMsg,
      created_at: new Date()
    };

    // 4. 存储报警
    await db(this.WATCHDOG_TABLE)
      .insert(alertRecord)
      .onConflict(['id'])
      .merge();

    return alertRecord;
  }

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