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

export interface PayoutAppeal {
  tenantId: string;
  payoutId: string;
  orderId: string;
  discrepancyAmount: number;
  appealReason: string;
}

/**
 * [BIZ_FIN_08] 回款差异自动申诉服务 (Discrepancy Auto-Appeal)
 * @description 基于 PayoutService 发现的金额差异，自动生成并提交平台申诉材料
 */
export class PayoutAppealService {
  private static readonly TABLE_NAME = 'cf_payout_appeals';

  /**
   * 自动生成并记录申诉 (BIZ_FIN_08)
   */
  static async triggerAutoAppeal(params: PayoutAppeal): Promise<number> {
    logger.info(`[PayoutAppeal] Triggering auto-appeal for Order: ${params.orderId}, Discrepancy: ${params.discrepancyAmount}`);

    // 1. 记录申诉
    const [id] = await db(this.TABLE_NAME).insert({
      tenant_id: params.tenantId,
      payout_id: params.payoutId,
      order_id: params.orderId,
      discrepancy_amount: params.discrepancyAmount,
      appeal_reason: params.appealReason,
      status: 'PENDING',
      created_at: new Date(),
      updated_at: new Date()
    });

    // 2. 模拟向平台提交申诉 (BIZ_FIN_08)
    await this.submitToPlatform(id, params);

    return id;
  }

  private static async submitToPlatform(appealId: number, params: PayoutAppeal): Promise<void> {
    logger.info(`[PayoutAppeal] [API_CALL] Submitting appeal ${appealId} to platform for Order ${params.orderId}`);

    // 模拟成功提交并获得外部 Case ID
    const externalCaseId = `CASE-${Date.now()}`;

    await db(this.TABLE_NAME).where({ id: appealId }).update({
      status: 'SUBMITTED',
      external_case_id: externalCaseId,
      updated_at: new Date()
    });
  }

  /**
   * 检查申诉状态并更新 (BIZ_FIN_08)
   */
  static async checkAppealStatus(appealId: number): Promise<void> {
    const appeal = await db(this.TABLE_NAME).where({ id: appealId }).first();
    if (!appeal) return;

    logger.info(`[PayoutAppeal] Checking status for Case: ${appeal.external_case_id}`);

    // 模拟申诉成功逻辑
    const status: 'WON' | 'LOST' = Math.random() > 0.3 ? 'WON' : 'LOST';

    await db(this.TABLE_NAME).where({ id: appealId }).update({
      status,
      updated_at: new Date()
    });

    if (status === 'WON') {
      logger.info(`[PayoutAppeal] Appeal WON! Discrepancy ${appeal.discrepancy_amount} recovered.`);
      // 在实际业务中，可以触发财务模块记录这笔恢复的资金
    }
  }
}
