import db from '../../config/database';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '../../utils/logger';

interface Payout {
  id: string;
  tenantId: string;
  shopId: string;
  amount: number;
  currency: string;
  status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED';
  method: 'BANK_TRANSFER' | 'PAYPAL' | 'OTHER';
  bankAccountId?: string;
  paypalEmail?: string;
  transactionId?: string;
  scheduledDate: Date;
  completedDate?: Date;
  failureReason?: string;
  traceId: string;
  taskId: string;
  businessType: 'TOC' | 'TOB';
  createdAt: Date;
  updatedAt: Date;
}

export class PayoutService {
  private static readonly TABLE = 'cf_payout';

  static async createPayout(payoutData: Partial<Payout>): Promise<Payout> {
    const id = uuidv4();
    
    await db(this.TABLE).insert({
      id,
      ...payoutData,
      status: payoutData.status || 'PENDING',
      createdAt: new Date(),
      updatedAt: new Date()
    });
    
    return (await this.getPayoutById(id))!;
  }

  static async getPayoutById(id: string): Promise<Payout | null> {
    return await db(this.TABLE).where({ id }).first();
  }

  static async updatePayoutStatus(id: string, status: Payout['status'], failureReason?: string): Promise<Payout | null> {
    const updateData: any = {
      status,
      updatedAt: new Date()
    };
    
    if (status === 'COMPLETED') {
      updateData.completedDate = new Date();
    } else if (status === 'FAILED' && failureReason) {
      updateData.failureReason = failureReason;
    }
    
    await db(this.TABLE)
      .where({ id })
      .update(updateData);
    
    return await this.getPayoutById(id);
  }

  static async listPayouts(tenantId: string, filters?: any): Promise<Payout[]> {
    let query = db(this.TABLE).where({ tenantId });
    
    if (filters) {
      if (filters.status) query = query.where({ status: filters.status });
      if (filters.startDate) query = query.where('scheduledDate', '>=', filters.startDate);
      if (filters.endDate) query = query.where('scheduledDate', '<=', filters.endDate);
    }
    
    return await query.orderBy('scheduledDate', 'desc');
  }

  static async processPayouts(): Promise<void> {
    // 这里可以实现处理待处理的支付的逻辑
    const pendingPayouts = await db(this.TABLE)
      .where({ status: 'PENDING' })
      .where('scheduledDate', '<=', new Date());
    
    for (const payout of pendingPayouts) {
      try {
        // 模拟处理支付
        await this.updatePayoutStatus(payout.id, 'PROCESSING');
        
        // 这里可以添加实际的支付处理逻辑
        
        await this.updatePayoutStatus(payout.id, 'COMPLETED');
        logger.info(`[PayoutService] Payout processed successfully: ${payout.id}`);
      } catch (error) {
        logger.error(`[PayoutService] Error processing payout: ${payout.id}`, { error });
        await this.updatePayoutStatus(payout.id, 'FAILED', (error as Error).message);
      }
    }
  }
}
