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

export interface FundInvestment {
  id?: number;
  tenantId: string;
  amount: number;
  targetType: 'INFRASTRUCTURE' | 'AGI_TRAINING' | 'MARKET_EXPANSION';
  status: 'PENDING' | 'ACTIVE' | 'EXITED';
  yieldRate?: number;
}

/**
 * [BIZ_FIN_25] 主权财富基金与集体投资协议 (Sovereign Wealth Fund)
 * @description 核心逻辑：允许租户将闲置利润投入“生态主权财富基金”。
 * 基金通过 AGI 自动决策，投向基础设施优化、大规模 AGI 模型训练或新市场开拓。
 * 基于 Shapley Value 分摊收益，实现生态内部的资本循环与协同增长。
 */
export class SovereignWealthFundService {
  private static readonly FUND_TABLE = 'cf_sovereign_wealth_fund';
  private static readonly INVESTMENT_TABLE = 'cf_fund_investments';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasFundTable = await db.schema.hasTable(this.FUND_TABLE);
    if (!hasFundTable) {
      logger.info(`📦 Creating ${this.FUND_TABLE} table...`);
      await db.schema.createTable(this.FUND_TABLE, (table) => {
        table.increments('id').primary();
        table.float('total_aum').defaultTo(0); // 资产管理规模
        table.float('current_yield').defaultTo(0.05); // 当前收益率
        table.timestamp('updated_at').defaultTo(db.fn.now());
      });
      await db(this.FUND_TABLE).insert({ total_aum: 0 });
    }

    const hasInvestTable = await db.schema.hasTable(this.INVESTMENT_TABLE);
    if (!hasInvestTable) {
      logger.info(`📦 Creating ${this.INVESTMENT_TABLE} table...`);
      await db.schema.createTable(this.INVESTMENT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.float('amount').notNullable();
        table.string('target_type', 32).notNullable();
        table.string('status', 16).defaultTo('ACTIVE');
        table.float('yield_at_entry');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * 租户注入资金
   */
  static async invest(params: {
    tenantId: string;
    amount: number;
    target: FundInvestment['targetType'];
  }): Promise<number> {
    logger.info(`[WealthFund] Tenant ${params.tenantId} investing ${params.amount} into ${params.target}`);

    return await db.transaction(async (trx) => {
      // 1. 记录投资
      const [id] = await trx(this.INVESTMENT_TABLE).insert({
        tenant_id: params.tenantId,
        amount: params.amount,
        target_type: params.target,
        yield_at_entry: 0.05 // 模拟当前收益率
      });

      // 2. 更新基金总规模
      await trx(this.FUND_TABLE).increment('total_aum', params.amount);

      return id;
    });
  }

  /**
   * 计算并派发分红 (基于 Shapley Value 模拟)
   */
  static async distributeDividends() {
    logger.info('[WealthFund] Distributing fund dividends to all active investors...');
    
    const activeInvestments = await db(this.INVESTMENT_TABLE).where({ status: 'ACTIVE' });
    const fundInfo = await db(this.FUND_TABLE).first();
    const totalProfit = fundInfo.total_aum * fundInfo.current_yield;

    for (const invest of activeInvestments) {
      const share = (invest.amount / fundInfo.total_aum) * totalProfit;
      logger.info(`[WealthFund] Distributing ${share.toFixed(2)} to Tenant ${invest.tenant_id}`);
      // 实际应联动结算服务
    }
  }

  /**
   * 获取基金概览
   */
  static async getOverview() {
    const fund = await db(this.FUND_TABLE).first();
    const stats = await db(this.INVESTMENT_TABLE)
      .select('target_type')
      .sum('amount as total')
      .groupBy('target_type');

    return {
      totalAUM: fund.total_aum,
      currentYield: fund.current_yield,
      allocation: stats,
      updatedAt: fund.updated_at
    };
  }
}
