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

export interface PnlData {
  tenantId: string;
  shopId: string;
  period: string; // YYYY-MM-DD
  revenue: number;
  costOfGoods: number;
  shippingCost: number;
  marketingSpend: number;
  taxAmount: number;
}

/**
 * [BIZ_FIN_10] 多租户实时经营损益快照服务
 * @description 实时聚合各项经营成本，生成动态 P&L 快照，支持商户实时监控利润健康度
 */
export class PnlSnapshotService {
  private static readonly TABLE_NAME = 'cf_pnl_snapshots';

  /**
   * 生成并更新损益快照 (BIZ_FIN_10)
   */
  static async updateSnapshot(pnl: PnlData): Promise<void> {
    logger.info(`[PnlSnapshot] Updating snapshot for Tenant: ${pnl.tenantId}, Shop: ${pnl.shopId}, Period: ${pnl.period}`);

    const netProfit = pnl.revenue - pnl.costOfGoods - pnl.shippingCost - pnl.marketingSpend - pnl.taxAmount;

    // 1. 持久化快照记录
    await db(this.TABLE_NAME)
      .insert({
        tenant_id: pnl.tenantId,
        shop_id: pnl.shopId,
        period: pnl.period,
        revenue: pnl.revenue,
        cost_of_goods: pnl.costOfGoods,
        shipping_cost: pnl.shippingCost,
        marketing_spend: pnl.marketingSpend,
        tax_amount: pnl.taxAmount,
        net_profit: netProfit,
        created_at: new Date(),
        updated_at: new Date()
      })
      .onConflict(['tenant_id', 'shop_id', 'period'])
      .merge();

    // 2. 利润红线预警 (BIZ_FIN_10)
    await this.checkProfitAlert(pnl.tenantId, pnl.shopId, pnl.revenue, netProfit);
  }

  /**
   * 利润健康度检查
   */
  private static async checkProfitAlert(tenantId: string, shopId: string, revenue: number, netProfit: number): Promise<void> {
    const profitMargin = revenue > 0 ? netProfit / revenue : 0;
    
    // B2C 利润率红线: < 20% 触发预警
    if (profitMargin < 0.2) {
      logger.warn(`[PnlSnapshot] Low profit margin alert for Tenant ${tenantId}: ${(profitMargin * 100).toFixed(1)}%`);
      // 在实际业务中，可以记录到 AdviceService 或发送系统通知
    }
  }

  /**
   * 获取指定租户的 P&L 概览
   */
  static async getPnlSummary(tenantId: string, period: string): Promise<any> {
    return await db(this.TABLE_NAME).where({ tenant_id: tenantId, period }).first();
  }
}
