import { Request, Response } from 'express';
import { SettlementService } from '../../domains/Finance/SettlementService';
import { logger } from '../../utils/logger';

/**
 * [BIZ_FIN_08] 实时毛利计算与分账引擎 Controller
 */
export class SettlementController {
  /**
   * 计算并获取订单 P&L 快照
   * GET /api/v1/finance/settlement/:orderId
   */
  static async settleOrder(req: Request, res: Response) {
    try {
      const { orderId } = req.params;
      const { tenantId } = (req as any).traceContext;

      const snapshot = await SettlementService.settleOrder(tenantId, orderId as string);
      res.json({ success: true, data: snapshot });
    } catch (err: any) {
      logger.error(`[SettlementController] Settle order error: ${err.message}`);
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 获取结算汇总
   * GET /api/v1/finance/settlement/summary
   */
  static async getSummary(req: Request, res: Response) {
    try {
      const { tenantId } = (req as any).traceContext;
      const summary = await SettlementService.getSettlementSummary(tenantId);
      res.json({ success: true, data: summary });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }
}
