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

/**
 * [BIZ_FIN_193] 基于 AI 预测的年度财务预算自动生成 (Budgeting)
 * @description 联动业务蓝图，自动生成年度财务预算建议。
 */
export class FinancialPlanner {
  private static readonly BUDGET_TABLE = 'cf_financial_budgets';

  /**
   * 生成年度财务预算建议
   */
  static async generateAnnualBudget(tenantId: string, year: number) {
    logger.info(`[FinancialPlanner] Generating annual budget for year: ${year} for tenant: ${tenantId}`);

    // 1. 获取过去一年的销售额和支出额
    const previousYearStart = new Date(year - 1, 0, 1);
    const previousYearEnd = new Date(year - 1, 11, 31);

    const sales = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId })
      .andWhere('created_at', '>=', previousYearStart)
      .andWhere('created_at', '<=', previousYearEnd)
      .select(db.raw('SUM(total_amount) as totalSales'));

    const expenses = await db('cf_expenses')
      .where({ tenant_id: tenantId })
      .andWhere('created_at', '>=', previousYearStart)
      .andWhere('created_at', '<=', previousYearEnd)
      .select(db.raw('SUM(amount) as totalExpenses'));

    const totalSales = Number(sales[0].totalSales || 0);
    const totalExpenses = Number(expenses[0].totalExpenses || 0);

    // 2. 预测明年的预算 (假设 20% 增长)
    const growthRatio = 1.2;
    const projectedRevenue = totalSales * growthRatio;
    const projectedExpenses = totalExpenses * growthRatio;
    const projectedProfit = projectedRevenue - projectedExpenses;

    const budget = {
      id: `BD-${tenantId}-${year}`,
      tenantId,
      year,
      projectedRevenue: Number(projectedRevenue.toFixed(2)),
      projectedExpenses: Number(projectedExpenses.toFixed(2)),
      projectedProfit: Number(projectedProfit.toFixed(2)),
      status: 'DRAFT',
      created_at: new Date()
    };

    // 3. 存储预算记录
    await db(this.BUDGET_TABLE)
      .insert(budget)
      .onConflict(['id'])
      .merge();

    return budget;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.BUDGET_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.BUDGET_TABLE} table...`);
      await db.schema.createTable(this.BUDGET_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.integer('year').notNullable();
        table.decimal('projectedRevenue', 15, 2);
        table.decimal('projectedExpenses', 15, 2);
        table.decimal('projectedProfit', 15, 2);
        table.string('status', 20); // E.g., DRAFT, APPROVED, FINALIZED
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'year']);
      });
    }
  }
}
