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

interface UsageRecord {
  id: string;
  merchantId: string;
  feature: string;
  usage: number;
  source: string;
  createdAt: Date;
}

interface TrackOptions {
  merchantId: string;
  feature: string;
  usage: number;
  source: string;
}

export class UsageService {
  /**
   * 记录使用量
   */
  async track(options: TrackOptions): Promise<UsageRecord> {
    const { merchantId, feature, usage, source } = options;
    
    const record: UsageRecord = {
      id: uuidv4(),
      merchantId,
      feature,
      usage,
      source,
      createdAt: new Date()
    };
    
    try {
      await db('usage_logs').insert({
        id: record.id,
        merchant_id: record.merchantId,
        feature: record.feature,
        usage: record.usage,
        source: record.source,
        created_at: record.createdAt
      });
      
      console.log(`[UsageService] Tracked usage: ${feature} x ${usage} for merchant ${merchantId}`);
      return record;
    } catch (error) {
      console.error('[UsageService] Error tracking usage:', error);
      throw error;
    }
  }
  
  /**
   * 获取商户的使用量记录
   */
  async getUsageByMerchant(merchantId: string, feature?: string): Promise<UsageRecord[]> {
    try {
      let query = db('usage_logs').where({ merchant_id: merchantId });
      
      if (feature) {
        query = query.where({ feature });
      }
      
      const records = await query.orderBy('created_at', 'desc');
      
      return records.map((record: any) => ({
        id: record.id,
        merchantId: record.merchant_id,
        feature: record.feature,
        usage: record.usage,
        source: record.source,
        createdAt: record.created_at
      }));
    } catch (error) {
      console.error('[UsageService] Error getting usage:', error);
      throw error;
    }
  }
  
  /**
   * 获取指定时间范围内的使用量
   */
  async getUsageByTimeRange(merchantId: string, startDate: Date, endDate: Date): Promise<UsageRecord[]> {
    try {
      const records = await db('usage_logs')
        .where({ merchant_id: merchantId })
        .where('created_at', '>=', startDate)
        .where('created_at', '<=', endDate)
        .orderBy('created_at', 'desc');
      
      return records.map((record: any) => ({
        id: record.id,
        merchantId: record.merchant_id,
        feature: record.feature,
        usage: record.usage,
        source: record.source,
        createdAt: record.created_at
      }));
    } catch (error) {
      console.error('[UsageService] Error getting usage by time range:', error);
      throw error;
    }
  }
  
  /**
   * 计算商户的总使用量
   */
  async calculateTotalUsage(merchantId: string, feature?: string): Promise<number> {
    try {
      let query = db('usage_logs').where({ merchant_id: merchantId });
      
      if (feature) {
        query = query.where({ feature });
      }
      
      const result = await query.sum('usage as total');
      return result[0].total || 0;
    } catch (error) {
      console.error('[UsageService] Error calculating total usage:', error);
      throw error;
    }
  }
}

export default new UsageService();
