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

export interface TaxPlanningInput {
  tenantId: string;
  originCountry: string;
  targetCountries: string[];
  productCategories: string[];
  estimatedAnnualTurnover: number;
}

export interface TaxStrategy {
  targetCountry: string;
  optimalStructure: string; // e.g., 'OSS', 'IOSS', 'Local Entity'
  estimatedTaxRate: number;
  complianceRequirements: string[];
  savingOpportunities: string[];
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
}

/**
 * [BIZ_FIN_11] 智能税务筹划与最优申报路径 (AI Tax Planning)
 * @description 利用 AI 分析全球税法，为租户提供最优的税务结构建议与合规申报路径。
 */
export class TaxPlanningService {
  private static readonly STRATEGY_TABLE = 'cf_tax_strategies';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.STRATEGY_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.STRATEGY_TABLE} table...`);
      await db.schema.createTable(this.STRATEGY_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('target_country', 50).notNullable();
        table.string('optimal_structure', 100);
        table.decimal('estimated_tax_rate', 5, 4);
        table.json('compliance_requirements');
        table.json('saving_opportunities');
        table.string('risk_level', 20);
        table.timestamps(true, true);
        table.unique(['tenant_id', 'target_country']);
      });
    }
  }

  /**
   * 生成税务筹划建议
   */
  static async generateTaxPlan(input: TaxPlanningInput): Promise<TaxStrategy[]> {
    // [BIZ_GOV_06] 功能开关校验
    if (!(await FeatureGovernanceService.isEnabled('BIZ_FIN_TAX_PLANNING', input.tenantId))) {
      logger.info(`[TaxAI] Service is disabled for Tenant ${input.tenantId}`);
      return [];
    }

    logger.info(`[TaxAI] Generating plan for tenant ${input.tenantId}`);

    try {
      // 1. 调用 AI 进行税务分析 (此处为模拟)
      const strategies: TaxStrategy[] = [];
      
      for (const country of input.targetCountries) {
        const aiStrategy = await this.requestAISuggestion(input, country);
        if (aiStrategy) {
          strategies.push(aiStrategy);

          // 2. 持久化到数据库
          await db(this.STRATEGY_TABLE)
            .insert({
              tenant_id: input.tenantId,
              target_country: country,
              optimal_structure: aiStrategy.optimalStructure,
              estimated_tax_rate: aiStrategy.estimatedTaxRate,
              compliance_requirements: JSON.stringify(aiStrategy.complianceRequirements),
              saving_opportunities: JSON.stringify(aiStrategy.savingOpportunities),
              risk_level: aiStrategy.riskLevel,
              created_at: new Date(),
              updated_at: new Date()
            })
            .onConflict(['tenant_id', 'target_country'])
            .merge();
        }
      }

      return strategies;
    } catch (err: any) {
      logger.error(`[TaxAI] Planning failed: ${err.message}`);
      throw err;
    }
  }

  /**
   * 模拟向 AI 请求建议
   */
  private static async requestAISuggestion(input: TaxPlanningInput, targetCountry: string): Promise<TaxStrategy | null> {
    // 模拟逻辑：如果是欧盟国家，建议 OSS
    const isEU = ['DE', 'FR', 'IT', 'ES', 'NL'].includes(targetCountry);
    
    return {
      targetCountry,
      optimalStructure: isEU ? 'EU OSS (One Stop Shop)' : 'Local VAT Registration',
      estimatedTaxRate: isEU ? 0.19 : 0.15,
      complianceRequirements: [
        'Monthly VAT return filing',
        'Invoice retention for 10 years',
        'OSS registration certificate'
      ],
      savingOpportunities: [
        'Input tax deduction on logistics',
        'Threshold-based exemptions'
      ],
      riskLevel: 'LOW'
    };
  }

  /**
   * 获取租户的税务筹划方案
   */
  static async getTenantStrategies(tenantId: string): Promise<TaxStrategy[]> {
    const records = await db(this.STRATEGY_TABLE).where({ tenant_id: tenantId });
    return records.map(r => ({
      targetCountry: r.target_country,
      optimalStructure: r.optimal_structure,
      estimatedTaxRate: r.estimated_tax_rate,
      complianceRequirements: JSON.parse(r.compliance_requirements || '[]'),
      savingOpportunities: JSON.parse(r.saving_opportunities || '[]'),
      riskLevel: r.risk_level
    }));
  }
}
