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

export interface PayoutStatement {
  tenantId: string;
  platform: string;
  externalPayoutId: string;
  totalAmount: number;
  currency: string;
  payoutDate: Date;
  orderItems: { externalOrderId: string; amount: number; fee: number }[];
}

/**
 * [BIZ_FIN_04] 自动化回款匹配与对账服务
 * @description 对接平台账单，实现订单与实际到账金额的自动勾稽
 */
export class PayoutService {
  private static readonly PAYOUT_TABLE = 'cf_payout_statements';

  /**
   * 导入并处理平台回款账单 (BIZ_FIN_04)
   */
  static async processPayout(payout: PayoutStatement): Promise<void> {
    logger.info(`[Payout] Processing payout ${payout.externalPayoutId} for ${payout.platform}, Tenant: ${payout.tenantId}`);

    // 1. 记录回款主记录
    const [payoutId] = await db(this.PAYOUT_TABLE).insert({
      tenant_id: payout.tenantId,
      platform: payout.platform,
      external_payout_id: payout.externalPayoutId,
      total_amount: payout.totalAmount,
      currency: payout.currency,
      status: 'PENDING',
      payout_date: payout.payoutDate,
      created_at: new Date(),
      updated_at: new Date()
    });

    // 2. 逐笔对账匹配
    let matchedCount = 0;
    let discrepancyCount = 0;

    for (const item of payout.orderItems) {
      const isMatched = await this.matchOrder(item, payout.tenantId);
      if (isMatched) matchedCount++;
      else discrepancyCount++;
    }

    // 3. 更新对账状态
    const finalStatus = discrepancyCount === 0 ? 'MATCHED' : 'DISCREPANCY';
    await db(this.PAYOUT_TABLE).where({ id: payoutId }).update({
      status: finalStatus,
      updated_at: new Date()
    });

    logger.info(`[Payout] Payout ${payout.externalPayoutId} completed. Matched: ${matchedCount}, Discrepancies: ${discrepancyCount}`);
  }

  /**
   * 订单对账匹配逻辑 (BIZ_FIN_04)
   */
  private static async matchOrder(item: { externalOrderId: string; amount: number; fee: number }, tenantId: string): Promise<boolean> {
    // 查找内部订单
    const order = await db('cf_orders')
      .where({ tenant_id: tenantId, id: item.externalOrderId })
      .first();

    if (!order) {
      logger.warn(`[Payout] Order ${item.externalOrderId} not found in our system for payout matching.`);
      return false;
    }

    // 校验金额差异
    // 售价 - 平台费 = 实际回款?
    const expectedPayout = order.selling_price - item.fee;
    const diff = Math.abs(expectedPayout - item.amount);

    if (diff > 0.01) {
      logger.error(`[Payout] Discrepancy for order ${order.id}: Expected ${expectedPayout.toFixed(2)}, Got ${item.amount.toFixed(2)} (Diff: ${diff.toFixed(2)})`);
      return false;
    }

    // 标记订单为已结算
    await db('cf_orders').where({ id: order.id }).update({
      status: 'RECONCILED',
      updated_at: new Date()
    });

    return true;
  }
}
