import { logger } from '../utils/logger';
import { RBACService, Role } from './RBACService';
import { BillingService } from './BillingService';
import { PaymentService } from './PaymentService';

export interface Feature {
  id: string;
  name: string;
  description: string;
  price: number;
  billingCycle: 'monthly' | 'yearly';
  status: 'ACTIVE' | 'INACTIVE' | 'UPCOMING';
  features: string[];
  createdAt: Date;
  updatedAt: Date;
}

export interface FeatureActivation {
  id: string;
  tenantId: string;
  shopId: string;
  featureId: string;
  status: 'PENDING' | 'ACTIVE' | 'EXPIRED' | 'CANCELLED';
  startDate: Date;
  endDate: Date;
  paymentStatus: 'PENDING' | 'COMPLETED' | 'FAILED';
  traceId: string;
  taskId: string;
  businessType: 'TOC' | 'TOB';
  createdAt: Date;
  updatedAt: Date;
}

export interface Payment {
  id: string;
  tenantId: string;
  shopId: string;
  amount: number;
  currency: string;
  method: 'credit_card' | 'paypal' | 'bank_transfer';
  status: 'PENDING' | 'COMPLETED' | 'FAILED' | 'REFUNDED';
  type: 'feature' | 'order';
  relatedId: string;
  transactionId: string;
  traceId: string;
  taskId: string;
  businessType: 'TOC' | 'TOB';
  createdAt: Date;
  updatedAt: Date;
}

export interface ActivateFeatureParams {
  tenantId: string;
  shopId: string;
  featureId: string;
  paymentMethod: 'credit_card' | 'paypal' | 'bank_transfer';
  traceId: string;
  taskId: string;
  businessType: 'TOC' | 'TOB';
}

export interface FeatureActivationResult {
  success: boolean;
  activation: FeatureActivation;
  payment?: Payment;
  message: string;
}

export class FeatureActivationService {
  /**
   * 初始化数据库表
   */
  static async initTable() {
    logger.info('🚀 FeatureActivationService table initialized');
    // 这里可以添加数据库表初始化逻辑
  }

  /**
   * 获取功能列表
   */
  static async getFeatures(traceId: string): Promise<Feature[]> {
    logger.info('[FeatureActivationService] Getting features', { traceId });
    // 这里可以添加获取功能列表的逻辑
    return [
      {
        id: 'feature_1',
        name: '基础版',
        description: '基础功能',
        price: 99,
        billingCycle: 'monthly',
        status: 'ACTIVE',
        features: ['商品管理', '订单管理', '基础报表'],
        createdAt: new Date(),
        updatedAt: new Date()
      },
      {
        id: 'feature_2',
        name: '专业版',
        description: '专业功能',
        price: 199,
        billingCycle: 'monthly',
        status: 'ACTIVE',
        features: ['商品管理', '订单管理', '高级报表', 'API接入', '多店铺管理'],
        createdAt: new Date(),
        updatedAt: new Date()
      }
    ];
  }

  /**
   * 检查功能访问权限
   */
  static async checkAccess(tenantId: string, shopId: string, featureId: string, traceId: string): Promise<{ allowed: boolean; reason: string }> {
    logger.info(`[FeatureActivationService] Checking access for feature: ${featureId}`, { traceId });
    
    // 1. 检查功能是否存在
    const features = await this.getFeatures(traceId);
    const feature = features.find(f => f.id === featureId);
    if (!feature) {
      return { allowed: false, reason: 'Feature not found' };
    }
    
    // 2. 检查功能是否激活
    const activation = await this.getActivationStatus(tenantId, shopId, featureId, traceId);
    if (activation && activation.status === 'ACTIVE') {
      return { allowed: true, reason: 'Feature is already active' };
    }
    
    // 3. 检查功能是否需要付费
    if (feature.price > 0) {
      return { allowed: false, reason: 'Feature requires payment' };
    }
    
    return { allowed: true, reason: 'Feature is free' };
  }

  /**
   * 激活功能
   */
  static async activateFeature(params: ActivateFeatureParams): Promise<FeatureActivationResult> {
    logger.info(`[FeatureActivationService] Activating feature: ${params.featureId} for tenant: ${params.tenantId}`, { traceId: params.traceId });
    
    // 1. 检查访问权限
    const accessCheck = await this.checkAccess(params.tenantId, params.shopId, params.featureId, params.traceId);
    if (!accessCheck.allowed && accessCheck.reason !== 'Feature requires payment') {
      return {
        success: false,
        activation: {
          id: 'activation_' + Date.now(),
          tenantId: params.tenantId,
          shopId: params.shopId,
          featureId: params.featureId,
          status: 'PENDING',
          startDate: new Date(),
          endDate: new Date(),
          paymentStatus: 'PENDING',
          traceId: params.traceId,
          taskId: params.taskId,
          businessType: params.businessType,
          createdAt: new Date(),
          updatedAt: new Date()
        },
        message: accessCheck.reason
      };
    }
    
    // 2. 创建激活记录
    const activation: FeatureActivation = {
      id: 'activation_' + Date.now(),
      tenantId: params.tenantId,
      shopId: params.shopId,
      featureId: params.featureId,
      status: 'PENDING',
      startDate: new Date(),
      endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30天
      paymentStatus: 'PENDING',
      traceId: params.traceId,
      taskId: params.taskId,
      businessType: params.businessType,
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    // 3. 如果功能需要付费，创建支付订单
    if (accessCheck.reason === 'Feature requires payment') {
      const features = await this.getFeatures(params.traceId);
      const feature = features.find(f => f.id === params.featureId);
      const amount = feature?.price || 0;
      
      const payment = await PaymentService.createPayment({
        tenantId: params.tenantId,
        shopId: params.shopId,
        amount,
        currency: 'USD',
        method: params.paymentMethod,
        type: 'feature',
        relatedId: activation.id,
        traceId: params.traceId,
        taskId: params.taskId,
        businessType: params.businessType
      });
      
      return {
        success: true,
        activation,
        payment,
        message: 'Feature activation initiated successfully'
      };
    }
    
    // 4. 如果功能是免费的，直接激活
    activation.status = 'ACTIVE';
    activation.paymentStatus = 'COMPLETED';
    
    // 5. 授予用户相应的权限
    await RBACService.assignRole('user_1', Role.OPERATOR, params.tenantId, params.shopId);
    logger.info(`[FeatureActivationService] Permissions granted to user`, { traceId: params.traceId });
    
    // 6. 生成账单记录
    const billResult = await BillingService.createBill({
      tenantId: params.tenantId,
      shopId: params.shopId,
      type: 'FEATURE',
      amount: 0,
      currency: 'USD',
      relatedId: activation.id,
      traceId: params.traceId,
      taskId: params.taskId,
      businessType: params.businessType
    });
    logger.info(`[FeatureActivationService] Bill generated: ${billResult.bill.id} for activation: ${activation.id}`, { traceId: params.traceId });
    
    return {
      success: true,
      activation,
      message: 'Feature activated successfully'
    };
  }

  /**
   * 处理支付
   */
  static async processPayment(paymentId: string, traceId: string): Promise<Payment> {
    logger.info(`[FeatureActivationService] Processing payment: ${paymentId}`, { traceId });
    
    // 1. 获取支付信息
    const payment = await PaymentService.getPayment(paymentId, traceId);
    if (!payment) {
      throw new Error('Payment not found');
    }
    
    // 2. 处理支付（模拟支付成功）
    const updatedPayment = await PaymentService.updatePaymentStatus(paymentId, 'COMPLETED', traceId);
    
    // 3. 如果支付成功，更新功能激活状态并授予权限
    if (updatedPayment.status === 'COMPLETED' && updatedPayment.type === 'feature') {
      logger.info(`[FeatureActivationService] Payment completed, updating activation status and granting permissions`, { traceId });
      
      // 4. 更新激活状态
      const activation: FeatureActivation = {
        id: updatedPayment.relatedId || 'activation_1',
        tenantId: updatedPayment.tenantId,
        shopId: updatedPayment.shopId,
        featureId: 'feature_1', // 这里应该从相关记录中获取
        status: 'ACTIVE',
        startDate: new Date(),
        endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        paymentStatus: 'COMPLETED',
        traceId,
        taskId: updatedPayment.taskId,
        businessType: updatedPayment.businessType,
        createdAt: new Date(),
        updatedAt: new Date()
      };
      
      // 5. 授予用户相应的权限
      await RBACService.assignRole('user_1', Role.OPERATOR, updatedPayment.tenantId, updatedPayment.shopId);
      logger.info(`[FeatureActivationService] Permissions granted to user`, { traceId });
      
      // 6. 生成账单记录
      const billResult = await BillingService.createBill({
        tenantId: updatedPayment.tenantId,
        shopId: updatedPayment.shopId,
        type: 'FEATURE',
        amount: updatedPayment.amount,
        currency: updatedPayment.currency,
        relatedId: updatedPayment.relatedId,
        traceId,
        taskId: updatedPayment.taskId,
        businessType: updatedPayment.businessType
      });
      logger.info(`[FeatureActivationService] Bill generated: ${billResult.bill.id} for payment: ${paymentId}`, { traceId });
    }
    
    return updatedPayment;
  }

  /**
   * 获取功能激活状态
   */
  static async getActivationStatus(tenantId: string, shopId: string, featureId: string, traceId: string): Promise<FeatureActivation | null> {
    logger.info(`[FeatureActivationService] Getting activation status for feature: ${featureId}`, { traceId });
    // 这里可以添加获取功能激活状态的逻辑
    return null;
  }

  /**
   * 取消功能激活
   */
  static async cancelActivation(activationId: string, traceId: string): Promise<FeatureActivation> {
    logger.info(`[FeatureActivationService] Cancelling activation: ${activationId}`, { traceId });
    // 这里可以添加取消功能激活的逻辑
    
    return {
      id: activationId,
      tenantId: 'tenant_1',
      shopId: 'shop_1',
      featureId: 'feature_1',
      status: 'CANCELLED',
      startDate: new Date(),
      endDate: new Date(),
      paymentStatus: 'COMPLETED',
      traceId,
      taskId: 'task_1',
      businessType: 'TOC',
      createdAt: new Date(),
      updatedAt: new Date()
    };
  }

  /**
   * 续费功能
   */
  static async renewActivation(activationId: string, traceId: string): Promise<FeatureActivationResult> {
    logger.info(`[FeatureActivationService] Renewing activation: ${activationId}`, { traceId });
    // 这里可以添加续费功能的逻辑
    
    const activation: FeatureActivation = {
      id: activationId,
      tenantId: 'tenant_1',
      shopId: 'shop_1',
      featureId: 'feature_1',
      status: 'ACTIVE',
      startDate: new Date(),
      endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30天
      paymentStatus: 'PENDING',
      traceId,
      taskId: 'task_1',
      businessType: 'TOC',
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    return {
      success: true,
      activation,
      message: 'Feature renewed successfully'
    };
  }
}
