// BEIE Profile Service
// Behavioral profile management

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { v4 as uuidv4 } from 'uuid';
import { beieMetricsService } from './beie-metrics.service';


export interface CreateProfileRequest {
  entityId: string;
  entityType: string; // retail_cbdc_user, institution, sovereign
}

export interface ProfileResult {
  profileId: string;
  riskLevel: string;
}

export class BeieProfileService {
  /**
   * Create or update behavioral profile
   */
  async createOrUpdateProfile(request: CreateProfileRequest): Promise<ProfileResult> {
    // Calculate all metrics
    const ccv = await beieMetricsService.calculateMetric({
      entityId: request.entityId,
      entityType: request.entityType,
      metricType: 'ccv',
    });

    const ilb = await beieMetricsService.calculateMetric({
      entityId: request.entityId,
      entityType: request.entityType,
      metricType: 'ilb',
    });

    const srp = await beieMetricsService.calculateMetric({
      entityId: request.entityId,
      entityType: request.entityType,
      metricType: 'srp',
    });

    // Calculate risk level
    const riskLevel = this.calculateRiskLevel(
      parseFloat(ccv.metricValue),
      parseFloat(ilb.metricValue),
      parseFloat(srp.metricValue)
    );

    // Check if profile exists
    const existing = await prisma.behavioralProfile.findFirst({
      where: {
        entityId: request.entityId,
        entityType: request.entityType,
      },
    });

    if (existing) {
      // Update existing profile
      const updated = await prisma.behavioralProfile.update({
        where: { profileId: existing.profileId },
        data: {
          ccvScore: new Decimal(ccv.metricValue),
          ilbScore: new Decimal(ilb.metricValue),
          srpScore: new Decimal(srp.metricValue),
          riskLevel,
          lastUpdated: new Date(),
        },
      });

      return {
        profileId: updated.profileId,
        riskLevel: updated.riskLevel,
      };
    } else {
      // Create new profile
      const profileId = `BEIE-PROF-${uuidv4()}`;

      const profile = await prisma.behavioralProfile.create({
        data: {
          profileId,
          entityId: request.entityId,
          entityType: request.entityType,
          ccvScore: new Decimal(ccv.metricValue),
          ilbScore: new Decimal(ilb.metricValue),
          srpScore: new Decimal(srp.metricValue),
          riskLevel,
        },
      });

      return {
        profileId: profile.profileId,
        riskLevel: profile.riskLevel,
      };
    }
  }

  /**
   * Calculate risk level from metrics
   */
  private calculateRiskLevel(ccv: number, ilb: number, srp: number): string {
    // Weighted risk calculation
    // Higher SRP = higher risk
    // Negative ILB (dumping) = higher risk
    // Lower CCV = higher risk (not spending)

    const riskScore = srp * 0.5 + Math.abs(ilb) * 0.3 + (1 - ccv) * 0.2;

    if (riskScore >= 0.7) {
      return 'critical';
    } else if (riskScore >= 0.5) {
      return 'high';
    } else if (riskScore >= 0.3) {
      return 'medium';
    } else {
      return 'low';
    }
  }

  /**
   * Get profile
   */
  async getProfile(entityId: string, entityType: string) {
    return await prisma.behavioralProfile.findFirst({
      where: {
        entityId,
        entityType,
      },
    });
  }

  /**
   * List profiles by risk level
   */
  async listProfiles(riskLevel?: string) {
    return await prisma.behavioralProfile.findMany({
      where: riskLevel ? { riskLevel } : undefined,
      orderBy: { lastUpdated: 'desc' },
    });
  }
}

export const beieProfileService = new BeieProfileService();

