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

/**
 * [BIZ_SOV_14] 跨节点资源共享配额管理 (Resource Quota)
 * @description 基于声誉分配跨节点算力/存储配额。
 */
export class NodeResourceQuotaService {
  private static readonly QUOTA_TABLE = 'cf_node_resource_quotas';

  /**
   * 根据声誉分分配资源配额
   * @param reputationScore 声誉分 (0-100)
   */
  static async allocateQuota(tenantId: string, nodeId: string, reputationScore: number) {
    logger.info(`[NodeResourceQuota] Allocating quota for node ${nodeId} with reputation ${reputationScore}`);

    // 配额算法：声誉分越高，分配的基础资源配额越多
    const computeQuota = reputationScore * 10; // 每分 10 单位算力
    const storageQuota = reputationScore * 100; // 每分 100 MB 存储

    const record = {
      tenant_id: tenantId,
      node_id: nodeId,
      compute_quota: computeQuota,
      storage_quota: storageQuota,
      reputation_score: reputationScore,
      updated_at: new Date()
    };

    await db(this.QUOTA_TABLE)
      .insert({ ...record, created_at: new Date() })
      .onConflict(['tenant_id', 'node_id'])
      .merge();

    return record;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.QUOTA_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.QUOTA_TABLE} table...`);
      await db.schema.createTable(this.QUOTA_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('node_id', 128).notNullable();
        table.decimal('compute_quota', 15, 2);
        table.decimal('storage_quota', 15, 2);
        table.decimal('reputation_score', 5, 2);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.timestamp('updated_at').defaultTo(db.fn.now());
        table.unique(['tenant_id', 'node_id']);
      });
    }
  }
}
