export type ViabilityLevel = "alta" | "media" | "baja";

export type RecommendationCardView = {
  id: string;
  score: number;
  publishDate?: string | null;
};

export type Module3Summary = {
  opportunities: number;
  highViability: number;
  mediumViability: number;
  averageCompatibility: number;
  newToReview: number;
};

export function getViabilityLevel(score: number): ViabilityLevel {
  if (score >= 70) {
    return "alta";
  }

  if (score >= 40) {
    return "media";
  }

  return "baja";
}

export function computeModule3Summary(totalResults: number, recommendations: RecommendationCardView[], now = new Date()): Module3Summary {
  const scores = recommendations
    .map((item) => Number(item.score))
    .filter((score) => Number.isFinite(score) && score >= 0)
    .slice(0, 100);

  const highViability = scores.filter((score) => getViabilityLevel(score) === "alta").length;
  const mediumViability = scores.filter((score) => getViabilityLevel(score) === "media").length;
  const averageCompatibility = scores.length ? Math.round(scores.reduce((sum, score) => sum + score, 0) / scores.length) : 0;

  const recentThreshold = new Date(now);
  recentThreshold.setDate(recentThreshold.getDate() - 7);

  const newToReview = recommendations.filter((item) => {
    if (!item.publishDate) {
      return false;
    }

    const parsedDate = new Date(item.publishDate);
    if (Number.isNaN(parsedDate.getTime())) {
      return false;
    }

    return parsedDate >= recentThreshold;
  }).length;

  return {
    opportunities: totalResults,
    highViability,
    mediumViability,
    averageCompatibility,
    newToReview,
  };
}
