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

export interface BillingQuota {
  tenantId: string;
  planId: string;
  seatsLimit: number;
  shopsLimit: number;
  nodesLimit: number;
  taskMonthlyLimit: number;
  aiCallLimit: number;
  usedSeats: number;
  usedShops: number;
  usedNodes: number;
  usedTasks: number;
  usedAiCalls: number;
  expiredAt: Date | null;
  resetAt: Date | null;
}

export interface SLAMetrics {
  uptime: number;
  responseTime: number;
  errorRate: number;
  taskSuccessRate: number;
}

export type ResourceType = 'seats' | 'shops' | 'nodes' | 'tasks' | 'ai_calls';

/**
 * [BIZ_BILL_01] 企业配额与订阅计费中心 (Quota & Subscription Billing)
 * @description 建立稳定经常性收入模型，支持 TOB/TOC 双线商业化
 */
export class BillingService {
  /**
   * 初始化数据库表
   */
  static async initTable() {
    // 1. Billing Plan 表 (套餐定义)
    const hasBillingTable = await db.schema.hasTable('cf_billing_plan');
    if (!hasBillingTable) {
      console.log('📦 Creating cf_billing_plan table...');
      await db.schema.createTable('cf_billing_plan', (table) => {
        table.string('id', 64).primary();
        table.string('name', 64).notNullable();
        table.integer('seats_limit').defaultTo(1);
        table.integer('shops_limit').defaultTo(1);
        table.integer('nodes_limit').defaultTo(1);
        table.integer('task_monthly_limit').defaultTo(100);
        table.integer('ai_call_limit').defaultTo(50);
        table.decimal('price', 10, 2);
        table.string('currency', 8).defaultTo('USD');
      });
      console.log('✅ Table cf_billing_plan created');

      // 插入默认套餐
      await db('cf_billing_plan').insert([
        { id: 'free', name: 'Free Plan', seats_limit: 1, shops_limit: 1, nodes_limit: 1, task_monthly_limit: 100, ai_call_limit: 50, price: 0 },
        { id: 'pro', name: 'Pro Plan', seats_limit: 10, shops_limit: 5, nodes_limit: 3, task_monthly_limit: 1000, ai_call_limit: 500, price: 99.00 },
        { id: 'enterprise', name: 'Enterprise Plan', seats_limit: 100, shops_limit: 50, nodes_limit: 20, task_monthly_limit: 10000, ai_call_limit: 5000, price: 499.00 }
      ]);
    }

    // 2. Tenant Quota 表 (租户配额与用量)
    const hasQuotaTable = await db.schema.hasTable('cf_tenant_quota');
    if (!hasQuotaTable) {
      console.log('📦 Creating cf_tenant_quota table...');
      await db.schema.createTable('cf_tenant_quota', (table) => {
        table.string('tenant_id', 64).primary();
        table.string('plan_id', 64).notNullable();
        // Limits
        table.integer('seats_limit').defaultTo(0);
        table.integer('shops_limit').defaultTo(0);
        table.integer('nodes_limit').defaultTo(0);
        table.integer('task_monthly_limit').defaultTo(0);
        table.integer('ai_call_limit').defaultTo(0);
        // Usage
        table.integer('used_seats').defaultTo(0);
        table.integer('used_shops').defaultTo(0);
        table.integer('used_nodes').defaultTo(0);
        table.integer('used_tasks').defaultTo(0);
        table.integer('used_ai_calls').defaultTo(0);
        
        table.dateTime('expired_at').nullable();
        table.dateTime('reset_at').nullable(); // 任务/AI调用配额重置时间
        table.timestamps(true, true);
      });
      console.log('✅ Table cf_tenant_quota created');
    }
  }

  /**
   * 激活订阅套餐
   */
  static async subscribe(tenantId: string, planId: string): Promise<void> {
    const plan = await db('cf_billing_plan').where({ id: planId }).first();
    if (!plan) throw new Error(`Plan ${planId} not found`);

    const expiredAt = new Date();
    expiredAt.setMonth(expiredAt.getMonth() + 1); // 默认一个月有效期

    const quotaData = { 
      tenant_id: tenantId, 
      plan_id: planId, 
      seats_limit: plan.seats_limit, 
      shops_limit: plan.shops_limit, 
      nodes_limit: plan.nodes_limit, 
      task_monthly_limit: plan.task_monthly_limit, 
      ai_call_limit: plan.ai_call_limit, 
      expired_at: expiredAt, 
      reset_at: new Date(),
      updated_at: db.fn.now()
    };

    const existing = await db('cf_tenant_quota').where({ tenant_id: tenantId }).first();
    if (existing) {
      await db('cf_tenant_quota').where({ tenant_id: tenantId }).update(quotaData);
    } else {
      await db('cf_tenant_quota').insert({ ...quotaData, created_at: db.fn.now() });
    }

    logger.info(`[Billing] Tenant ${tenantId} subscribed to ${planId}`);
  }

  /**
   * 获取租户用量详情 (API 响应格式)
   */
  static async getUsage(tenantId: string) {
    const quota = await QuotaService.getQuota(tenantId);
    if (!quota) return null;

    return {
      planId: quota.planId,
      usage: {
        seats: { used: quota.usedSeats, limit: quota.seatsLimit, percent: (quota.usedSeats / quota.seatsLimit) * 100 },
        shops: { used: quota.usedShops, limit: quota.shopsLimit, percent: (quota.usedShops / quota.shopsLimit) * 100 },
        nodes: { used: quota.usedNodes, limit: quota.nodesLimit, percent: (quota.usedNodes / quota.nodesLimit) * 100 },
        tasks: { used: quota.usedTasks, limit: quota.taskMonthlyLimit, percent: (quota.usedTasks / quota.taskMonthlyLimit) * 100 },
        ai_calls: { used: quota.usedAiCalls, limit: quota.aiCallLimit, percent: (quota.usedAiCalls / quota.aiCallLimit) * 100 },
      },
      expiredAt: quota.expiredAt,
      resetAt: quota.resetAt
    };
  }

  /**
   * 配额控制：检查是否超出配额
   */
  static async checkQuota(tenantId: string, resourceType: ResourceType): Promise<{ allowed: boolean; message?: string }> {
    return QuotaService.checkQuota(tenantId, resourceType);
  }

  /**
   * 记录资源消耗
   */
  static async recordUsage(tenantId: string, resourceType: ResourceType, amount: number = 1): Promise<boolean> {
    logger.info(`[Billing] Recording ${amount} ${resourceType} usage for Tenant: ${tenantId}`);
    return QuotaService.incrementUsage(tenantId, resourceType, amount);
  }

  /**
   * 获取SLA指标
   */
  static async getSLAMetrics(tenantId: string): Promise<SLAMetrics> {
    logger.info(`[Billing] Getting SLA metrics for Tenant: ${tenantId}`);
    
    // 模拟SLA指标
    return {
      uptime: 99.9,
      responseTime: 150,
      errorRate: 0.1,
      taskSuccessRate: 99.5
    };
  }
}
