import { db } from '@/lib/db';

export function calculateRiskLevel(reportCount: number, evidenceCount: number): { level: 'low' | 'medium' | 'high' | 'critical'; score: number } {
  let score = 0;
  
  // Report count factor (0-50 points)
  if (reportCount >= 10) score += 50;
  else if (reportCount >= 5) score += 35;
  else if (reportCount >= 3) score += 20;
  else if (reportCount >= 2) score += 10;
  else score += 5;

  // Evidence factor (0-30 points)
  if (evidenceCount >= 5) score += 30;
  else if (evidenceCount >= 3) score += 20;
  else if (evidenceCount >= 1) score += 10;

  // Recency bonus (0-20 points)
  score += Math.min(20, reportCount * 4);

  score = Math.min(100, score);

  let level: 'low' | 'medium' | 'high' | 'critical';
  if (score >= 75) level = 'critical';
  else if (score >= 50) level = 'high';
  else if (score >= 25) level = 'medium';
  else level = 'low';

  return { level, score };
}

export async function updateRiskScore(entityType: string, entityValue: string) {
  const linkedEntities = await db.linkedEntity.findMany({
    where: { entityType, entityValue },
  });

  const reportIds = linkedEntities.map((e) => e.reportId);
  
  let evidenceCount = 0;
  if (reportIds.length > 0) {
    evidenceCount = await db.reportEvidence.count({
      where: { reportId: { in: reportIds } },
    });
  }

  const { level, score } = calculateRiskLevel(reportIds.length, evidenceCount);

  const lastReport = reportIds.length > 0
    ? await db.scamReport.findFirst({
        where: { id: { in: reportIds } },
        orderBy: { createdAt: 'desc' },
      })
    : null;

  await db.riskScore.upsert({
    where: { entityType_entityValue: { entityType, entityValue } },
    create: {
      entityType,
      entityValue,
      riskLevel: level,
      score,
      reportCount: reportIds.length,
      evidenceCount,
      lastReported: lastReport?.createdAt,
    },
    update: {
      riskLevel: level,
      score,
      reportCount: reportIds.length,
      evidenceCount,
      lastReported: lastReport?.createdAt,
    },
  });
}
