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

/**
 * [BIZ_FIN_180] 员工/Agent 操作导致的财务损失审计 (Loss)
 * @description 追踪员工或 Agent 操作导致的异常财务损失。
 */
export class FinancialAuditService {
  private static readonly LOSS_TABLE = 'cf_financial_loss_audits';

  /**
   * 执行财务损失审计
   */
  static async auditFinancialLoss(tenantId: string) {
    logger.info(`[FinancialAudit] Auditing financial loss for tenant: ${tenantId}`);

    // 1. 获取过去 30 天的所有审计日志
    const auditLogs = await db('cf_audit_logs')
      .where({ tenantId })
      .andWhere('action', 'in', ['REFUND_ORDER', 'CANCEL_ORDER', 'ADJUST_PRICE'])
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000));

    const lossRecords = [];

    for (const log of auditLogs) {
      const { id, actorId, action, resourceId, metaData } = log;
      
      // 2. 识别损失 (基于操作元数据)
      let estimatedLoss = 0;
      let reason = 'Normal operation';

      if (action === 'REFUND_ORDER') {
        estimatedLoss = Number(metaData.refundAmount || 0);
        reason = `Order ${resourceId} was refunded. Potential loss: ${estimatedLoss.toFixed(2)}`;
      } else if (action === 'CANCEL_ORDER') {
        estimatedLoss = Number(metaData.orderTotal || 0);
        reason = `Order ${resourceId} was canceled. Potential revenue loss: ${estimatedLoss.toFixed(2)}`;
      } else if (action === 'ADJUST_PRICE') {
        estimatedLoss = Number(metaData.priceDiff || 0);
        reason = `Price of ${resourceId} was adjusted down. Potential margin loss: ${estimatedLoss.toFixed(2)}`;
      }

      if (estimatedLoss > 0) {
        const lossRecord = {
          id: `FL-${tenantId}-${log.id}`,
          tenantId,
          actorId,
          action,
          resourceId,
          estimatedLoss: Number(estimatedLoss.toFixed(2)),
          reason,
          created_at: new Date()
        };

        lossRecords.push(lossRecord);

        // 3. 存储审计记录
        await db(this.LOSS_TABLE)
          .insert(lossRecord)
          .onConflict(['id'])
          .merge();
      }
    }

    return lossRecords;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.LOSS_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.LOSS_TABLE} table...`);
      await db.schema.createTable(this.LOSS_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('actorId', 64).notNullable();
        table.string('action', 64).notNullable();
        table.string('resourceId', 128);
        table.decimal('estimatedLoss', 15, 2);
        table.text('reason');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'actorId']);
      });
    }
  }
}
