/**
 * Referral Contest System
 * Monthly contests with bonus prizes for top referrers
 */

export interface ReferralContest {
  id: number;
  name: string;
  description: string;
  startDate: Date;
  endDate: Date;
  status: 'upcoming' | 'active' | 'ended' | 'completed';
  totalPrizePool: number; // Total SC to distribute
  prizeDistribution: PrizeDistribution[];
  participants: number;
  createdAt: Date;
}

export interface PrizeDistribution {
  rank: number; // 1st, 2nd, 3rd, etc.
  prizeAmount: number; // SC amount
  percentage?: number; // Percentage of pool
}

export interface ContestParticipant {
  id: number;
  contestId: number;
  userId: number;
  referralsCount: number;
  currentRank: number;
  prizeEarned?: number;
  status: 'active' | 'completed' | 'disqualified';
  joinedAt: Date;
}

export interface ContestLeaderboard {
  rank: number;
  playerName: string;
  referrals: number;
  prize: number;
  trend: 'up' | 'down' | 'stable';
}

/**
 * Predefined Contest Templates
 */
export const CONTEST_TEMPLATES = {
  monthly: {
    name: 'Monthly Referral Challenge',
    description: 'Compete with other players to earn the most referrals this month!',
    prizePool: 5000, // 5000 SC
    prizeDistribution: [
      { rank: 1, prizeAmount: 2000, percentage: 40 },
      { rank: 2, prizeAmount: 1200, percentage: 24 },
      { rank: 3, prizeAmount: 800, percentage: 16 },
      { rank: 4, prizeAmount: 500, percentage: 10 },
      { rank: 5, prizeAmount: 300, percentage: 6 },
      { rank: 6, prizeAmount: 200, percentage: 4 },
    ],
    duration: 30, // days
  },
  weekly: {
    name: 'Weekly Referral Blitz',
    description: 'Fast-paced weekly competition for quick referrers!',
    prizePool: 1000, // 1000 SC
    prizeDistribution: [
      { rank: 1, prizeAmount: 500, percentage: 50 },
      { rank: 2, prizeAmount: 250, percentage: 25 },
      { rank: 3, prizeAmount: 150, percentage: 15 },
      { rank: 4, prizeAmount: 100, percentage: 10 },
    ],
    duration: 7, // days
  },
  seasonal: {
    name: 'Seasonal Referral Extravaganza',
    description: 'Massive prizes for the ultimate referral champions!',
    prizePool: 20000, // 20000 SC
    prizeDistribution: [
      { rank: 1, prizeAmount: 8000, percentage: 40 },
      { rank: 2, prizeAmount: 5000, percentage: 25 },
      { rank: 3, prizeAmount: 3000, percentage: 15 },
      { rank: 4, prizeAmount: 2000, percentage: 10 },
      { rank: 5, prizeAmount: 1000, percentage: 5 },
      { rank: 6, prizeAmount: 1000, percentage: 5 },
    ],
    duration: 90, // days
  },
};

/**
 * Calculate prize for rank
 */
export function calculatePrizeForRank(
  rank: number,
  prizeDistribution: PrizeDistribution[]
): number {
  const prize = prizeDistribution.find(p => p.rank === rank);
  return prize?.prizeAmount || 0;
}

/**
 * Get contest status
 */
export function getContestStatus(startDate: Date, endDate: Date): 'upcoming' | 'active' | 'ended' {
  const now = new Date();
  if (now < startDate) return 'upcoming';
  if (now > endDate) return 'ended';
  return 'active';
}

/**
 * Calculate days remaining in contest
 */
export function calculateDaysRemaining(endDate: Date): number {
  const now = new Date();
  const daysRemaining = Math.ceil((endDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
  return Math.max(0, daysRemaining);
}

/**
 * Calculate contest progress percentage
 */
export function calculateContestProgress(startDate: Date, endDate: Date): number {
  const now = new Date();
  const totalDuration = endDate.getTime() - startDate.getTime();
  const elapsed = now.getTime() - startDate.getTime();
  return Math.round((elapsed / totalDuration) * 100);
}

/**
 * Generate leaderboard from participants
 */
export function generateLeaderboard(
  participants: ContestParticipant[],
  prizeDistribution: PrizeDistribution[]
): ContestLeaderboard[] {
  // Sort by referrals count (descending)
  const sorted = [...participants].sort((a, b) => b.referralsCount - a.referralsCount);

  return sorted.map((participant, index) => {
    const rank = index + 1;
    const prize = calculatePrizeForRank(rank, prizeDistribution);

    return {
      rank,
      playerName: `Player${participant.userId}`,
      referrals: participant.referralsCount,
      prize,
      trend: 'stable' as const, // Would be calculated based on previous position
    };
  });
}

/**
 * Validate contest creation
 */
export function validateContestCreation(
  startDate: Date,
  endDate: Date,
  prizePool: number
): { valid: boolean; reason?: string } {
  if (startDate >= endDate) {
    return { valid: false, reason: 'Start date must be before end date' };
  }

  if (prizePool <= 0) {
    return { valid: false, reason: 'Prize pool must be greater than 0' };
  }

  const now = new Date();
  if (endDate < now) {
    return { valid: false, reason: 'End date must be in the future' };
  }

  return { valid: true };
}

/**
 * Calculate total prize distribution
 */
export function calculateTotalPrizeDistribution(prizeDistribution: PrizeDistribution[]): number {
  return prizeDistribution.reduce((total, prize) => total + prize.prizeAmount, 0);
}

/**
 * Get contest template
 */
export function getContestTemplate(type: keyof typeof CONTEST_TEMPLATES) {
  return CONTEST_TEMPLATES[type];
}

/**
 * Create contest from template
 */
export function createContestFromTemplate(
  type: keyof typeof CONTEST_TEMPLATES,
  startDate: Date
): Partial<ReferralContest> {
  const template = CONTEST_TEMPLATES[type];
  const endDate = new Date(startDate);
  endDate.setDate(endDate.getDate() + template.duration);

  return {
    name: template.name,
    description: template.description,
    startDate,
    endDate,
    status: getContestStatus(startDate, endDate),
    totalPrizePool: template.prizePool,
    prizeDistribution: template.prizeDistribution,
  };
}

/**
 * Check if player qualifies for prize
 */
export function checkPrizeQualification(
  referralsCount: number,
  minReferralsForPrize: number = 1
): boolean {
  return referralsCount >= minReferralsForPrize;
}
