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

/**
 * [BIZ_FIN_172] 库存跌价准备自动计提建议 (Write-down)
 * @description 评估滞销库存及其对财务报表的影响，计提跌价准备。
 */
export class InventoryValueService {
  private static readonly VALUATION_TABLE = 'cf_inventory_valuations';

  /**
   * 评估库存价值与跌价风险
   */
  static async auditTenantInventoryValue(tenantId: string) {
    logger.info(`[InventoryValue] Auditing inventory value for tenant: ${tenantId}`);

    // 1. 获取当前所有库存项及其最近销售记录
    const stocks = await db('cf_inventory')
      .where({ tenant_id: tenantId })
      .select('sku_id', 'quantity', 'cost_price', 'updated_at');

    const valuations = [];

    for (const stock of stocks) {
      const { sku_id, quantity, cost_price, updated_at } = stock;
      
      // 2. 识别滞销周期 (从上次更新到现在)
      const lastUpdate = new Date(updated_at);
      const daysSinceLastUpdate = Math.floor((Date.now() - lastUpdate.getTime()) / (1000 * 60 * 60 * 24));

      // 3. 计算跌价比例 (简化模型)
      let writeDownRatio = 0;
      let status = 'HEALTHY';

      if (daysSinceLastUpdate > 180) { // 超过半年没动
        writeDownRatio = 0.5; // 计提 50% 跌价
        status = 'STAGNANT';
      } else if (daysSinceLastUpdate > 90) { // 超过三个月
        writeDownRatio = 0.2; // 计提 20% 跌价
        status = 'SLOW_MOVING';
      }

      const totalCost = quantity * cost_price;
      const writeDownAmount = totalCost * writeDownRatio;
      const netValue = totalCost - writeDownAmount;

      const valuation = {
        id: `VAL-${tenantId}-${sku_id}-${new Date().toISOString().split('T')[0]}`,
        tenantId,
        skuId: sku_id,
        quantity,
        totalCost: Number(totalCost),
        writeDownAmount: Number(writeDownAmount),
        netValue: Number(netValue),
        status,
        created_at: new Date()
      };

      valuations.push(valuation);

      // 4. 存储估值记录
      await db(this.VALUATION_TABLE)
        .insert(valuation)
        .onConflict(['id'])
        .merge();
    }

    return valuations;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.VALUATION_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.VALUATION_TABLE} table...`);
      await db.schema.createTable(this.VALUATION_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('skuId', 128).notNullable();
        table.integer('quantity');
        table.decimal('totalCost', 15, 2);
        table.decimal('writeDownAmount', 15, 2);
        table.decimal('netValue', 15, 2);
        table.string('status', 20); // E.g., HEALTHY, SLOW_MOVING, STAGNANT
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'skuId']);
      });
    }
  }
}
