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

export class PaymentRiskService {
  private static readonly RISK_TABLE = 'cf_payment_gateway_risks';

  static async initTable() {
    const hasTable = await db.schema.hasTable(this.RISK_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.RISK_TABLE} table...`);
      await db.schema.createTable(this.RISK_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.integer('totalOrders');
        table.integer('canceledOrders');
        table.decimal('cancellationRatio', 5, 4);
        table.string('riskLevel', 20);
        table.text('recommendation');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId']);
      });
    }
  }

  static async auditGatewayRisk(tenantId: string) {
    logger.info(`[PaymentRisk] Auditing gateway risk for tenant: ${tenantId}`);

    const stats = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId })
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(
        db.raw('COUNT(id) as totalOrders'),
        db.raw('SUM(CASE WHEN status = "CANCELED" THEN 1 ELSE 0 END) as canceledOrders')
      );

    const totalOrders = Number(stats[0].totalOrders || 0);
    const canceledOrders = Number(stats[0].canceledOrders || 0);
    const cancellationRatio = totalOrders > 0 ? canceledOrders / totalOrders : 0;

    let riskLevel = 'LOW';
    let recommendation = 'Normal operations';

    if (cancellationRatio > 0.2) {
      riskLevel = 'CRITICAL';
      recommendation = 'High cancellation rate detected (>20%). Gateway at risk of suspension.';
    } else if (cancellationRatio > 0.1) {
      riskLevel = 'MEDIUM';
      recommendation = 'Cancellation rate is elevated (>10%). Monitor closely.';
    }

    const riskRecord = {
      id: `GR-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      totalOrders,
      canceledOrders,
      cancellationRatio: Number(cancellationRatio.toFixed(4)),
      riskLevel,
      recommendation,
      created_at: new Date()
    };

    await db(this.RISK_TABLE)
      .insert(riskRecord)
      .onConflict(['id'])
      .merge();

    return riskRecord;
  }

  static async monitorPaymentGatewayRisk(tenantId: string, gatewayId: string): Promise<any> {
    logger.info(`[PaymentRisk] Monitoring gateway risk for Tenant: ${tenantId}, Gateway: ${gatewayId}`);

    try {
      const cancellationRate = 0.15;
      const threshold = 0.10;

      if (cancellationRate > threshold) {
        const advice = `GATEWAY RISK ALERT: Cancellation rate (${(cancellationRate * 100).toFixed(1)}%) is above the safe threshold (10%).`;

        await DecisionExplainabilityEngine.logDecision({
          tenantId,
          module: 'PAYMENT_SECURITY',
          resourceId: gatewayId,
          decisionType: 'GATEWAY_SUSPENSION_PREVENTION',
          causalChain: advice,
          factors: [
            { name: 'CancellationRate', value: (cancellationRate * 100).toFixed(1) + '%', weight: 0.9, impact: 'NEGATIVE' },
            { name: 'ThresholdRate', value: (threshold * 100).toFixed(1) + '%', weight: 0.1, impact: 'NEUTRAL' }
          ],
          traceId: 'payment-risk-' + Date.now()
        });

        return { success: true, riskLevel: 'HIGH', cancellationRate, advice, status: 'PENDING_REVIEW' };
      }

      return { success: true, riskLevel: 'LOW', message: 'Gateway risk is within limits' };
    } catch (err: any) {
      logger.error(`[PaymentRisk][WARN] Monitoring failed: ${err.message}`);
      return { success: false, error: err.message };
    }
  }
}