import prisma from '../lib/prisma.js';

// Type helper to convert Decimal to number
// Prisma Decimal has a toNumber() method
const toNumber = (value: any): number | null => {
  if (value == null) return null;
  if (typeof value === 'number') return value;
  // Check if it's a Prisma Decimal (has toNumber method)
  if (value && typeof value.toNumber === 'function') {
    return value.toNumber();
  }
  const num = Number(value);
  return isNaN(num) ? null : num;
};

export interface PropertyScore {
  finalScore: number;
  featuredBoost: number;
  engagementScore: number;
  recencyScore: number;
  agentBoost: number;
  qualityScore: number;
  priceCompetitivenessScore: number;
  locationPopularityScore: number;
}

interface PropertyWithRelations {
  id: string;
  featured: boolean;
  featuredUntil: Date | null;
  publishedAt: Date | null;
  viewCount: number;
  clickCount: number;
  favoriteCount: number;
  messageCount: number;
  verified: boolean;
  description: string | null;
  price: number | any | null; // Prisma Decimal type (has toNumber() method)
  bedrooms: number | null;
  bathrooms: number | null;
  areaSqft: number | null;
  address: string | null;
  city?: string | null;
  subCity?: string | null;
  propertyType?: string | null;
  listingType?: string | null;
  photos?: Array<{ id: string }>;
  amenities?: Array<{ id: string }>;
  owner?: {
    id: string;
    role: string;
    verified: boolean;
    agentProfile?: {
      verificationStatus: string;
    } | null;
  };
  boostRequests?: Array<{
    id: string;
    status: string;
    plan: {
      days: number;
    };
    createdAt: Date;
  }>;
}

/**
 * Calculate featured boost score (0-100)
 * Considers admin-manual featured, paid boost requests, and time decay
 */
function calculateFeaturedBoost(
  property: PropertyWithRelations,
  now: Date
): number {
  if (!property.featured) return 0;

  // Check if featured is still active
  if (property.featuredUntil && property.featuredUntil <= now) {
    return 0;
  }

  let baseScore = 100;
  let multiplier = 1.0;

  // Check for approved boost request (paid boost)
  const activeBoostRequest = property.boostRequests?.find(
    (br) => br.status === 'APPROVED'
  );

  if (activeBoostRequest) {
    // Paid boost gets 50% multiplier boost
    multiplier = 1.5;

    // Check if boost is expiring soon (within 3 days) - reduce multiplier slightly
    if (property.featuredUntil) {
      const daysRemaining =
        (property.featuredUntil.getTime() - now.getTime()) /
        (1000 * 60 * 60 * 24);
      if (daysRemaining < 3) {
        multiplier = 1.3; // Slightly reduced for expiring boosts
      }
    }
  } else {
    // Admin-manual featured gets 20% boost
    multiplier = 1.2;
  }

  // Apply time decay for featured properties older than 1 week
  if (property.publishedAt) {
    const daysSincePublished =
      (now.getTime() - property.publishedAt.getTime()) /
      (1000 * 60 * 60 * 24);
    if (daysSincePublished > 7) {
      // Reduce by 10% per week after first week
      const weeksOld = Math.floor((daysSincePublished - 7) / 7);
      const decayFactor = Math.max(0.5, 1 - weeksOld * 0.1); // Minimum 50% of original score
      multiplier *= decayFactor;
    }
  }

  return Math.min(100, baseScore * multiplier);
}

/**
 * Calculate engagement score based on views, clicks, favorites, and messages
 * Uses logarithmic scaling for very high counts
 */
function calculateEngagementScore(property: PropertyWithRelations): number {
  // Normalize metrics with logarithmic scaling to prevent outliers from dominating
  const logScale = (value: number, base: number) => {
    if (value <= 0) return 0;
    return Math.min(100, (Math.log10(value + 1) / Math.log10(base + 1)) * 100);
  };

  const viewScore = logScale(property.viewCount || 0, 100); // 100 views = ~100 points
  const clickScore = logScale(property.clickCount || 0, 20); // 20 clicks = ~100 points
  const favoriteScore = logScale(property.favoriteCount || 0, 10); // 10 favorites = ~100 points
  const messageScore = logScale(property.messageCount || 0, 5); // 5 messages = ~100 points

  // Weighted average
  return (
    viewScore * 0.3 +
    clickScore * 0.3 +
    favoriteScore * 0.25 +
    messageScore * 0.15
  );
}

/**
 * Calculate recency score based on how recently the property was published
 * Uses exponential decay
 */
function calculateRecencyScore(
  property: PropertyWithRelations,
  now: Date
): number {
  if (!property.publishedAt) return 20; // Default low score for unpublished

  const daysSincePublished =
    (now.getTime() - property.publishedAt.getTime()) / (1000 * 60 * 60 * 24);

  // Exponential decay: 100 * e^(-days/7)
  // First day: ~100 points
  // First week: ~37 points
  // First month: ~2 points
  const decayRate = 7; // Half-life of 7 days
  const score = 100 * Math.exp(-daysSincePublished / decayRate);

  // Apply step bonuses for very recent properties
  if (daysSincePublished < 1) return 100; // First day: max boost
  if (daysSincePublished < 7) return Math.max(80, score); // First week: high boost
  if (daysSincePublished < 30) return Math.max(60, score); // First month: medium boost

  return Math.max(20, score); // Minimum 20 points for older properties
}

/**
 * Calculate agent boost score based on subscription tier and verification
 */
async function calculateAgentBoost(
  owner: PropertyWithRelations['owner'],
  cachedSubscription?: any
): Promise<number> {
  if (!owner || owner.role !== 'AGENT') return 0;

  let score = 0;

  // Use cached subscription if provided, otherwise fetch
  let activeSubscription = cachedSubscription;
  if (!activeSubscription && owner.id) {
    activeSubscription = await prisma.agentSubscription.findFirst({
      where: {
        userId: owner.id,
        status: 'ACTIVE',
        endDate: {
          gt: new Date(),
        },
      },
      include: {
        plan: true,
      },
    });
  }

  if (activeSubscription) {
    // Base agent boost
    score += 50;

    // Plan tier multiplier
    const planName = activeSubscription.plan.name.toLowerCase();
    if (planName.includes('premium') || planName.includes('enterprise')) {
      score += 30; // Premium/Enterprise agents get extra boost
    } else if (planName.includes('basic')) {
      score += 10; // Basic plan gets small boost
    }

    // Verified agent boost
    if (owner.agentProfile?.verificationStatus === 'VERIFIED') {
      score += 20;
    }
  } else {
    // Unsubscribed agents still get small boost if verified
    if (owner.agentProfile?.verificationStatus === 'VERIFIED') {
      score += 15;
    }
  }

  return Math.min(100, score);
}

/**
 * Calculate quality score based on completeness, verification, and data quality
 */
function calculateQualityScore(
  property: PropertyWithRelations,
  owner: PropertyWithRelations['owner']
): number {
  let score = 0;

  // Photo completeness (max 30 points)
  const photoCount = property.photos?.length || 0;
  score += Math.min(30, (photoCount / 10) * 30); // 10+ photos = 30 points

  // Description quality (max 20 points)
  const descLength = property.description?.length || 0;
  score += Math.min(20, (descLength / 500) * 20); // 500+ chars = 20 points

  // Amenities (max 15 points)
  const amenityCount = property.amenities?.length || 0;
  score += Math.min(15, (amenityCount / 5) * 15); // 5+ amenities = 15 points

  // Verification (max 20 points)
  if (property.verified) score += 20;
  if (owner?.verified) score += 10;
  if (owner?.agentProfile?.verificationStatus === 'VERIFIED') score += 10;

  // Required fields completeness (max 15 points)
  const requiredFields = ['price', 'bedrooms', 'bathrooms', 'areaSqft', 'address'];
  const filledFields = requiredFields.filter((f) => {
    const value = property[f as keyof PropertyWithRelations];
    return value != null && value !== '';
  }).length;
  score += (filledFields / requiredFields.length) * 15;

  return Math.min(100, score);
}

/**
 * Calculate price competitiveness score (0-100)
 * Properties priced competitively relative to similar properties get higher scores
 */
function calculatePriceCompetitivenessScore(
  property: PropertyWithRelations,
  similarProperties: PropertyWithRelations[]
): number {
  // Convert price to number if it's Decimal
  const propertyPrice = toNumber(property.price);
  
  if (!propertyPrice || similarProperties.length === 0) return 50; // Neutral score if no data

  // OPTIMIZED: Filter similar properties (already pre-filtered by type, now just filter by area and price)
  // Limit to 50 similar properties max to prevent excessive computation
  const similar = similarProperties
    .filter((p) => {
      if (p.id === property.id) return false;
      if (!p.price) return false;
      
      // Similar area (±20%)
      if (property.areaSqft && p.areaSqft) {
        const areaDiff = Math.abs(p.areaSqft - property.areaSqft) / property.areaSqft;
        if (areaDiff > 0.2) return false;
      }
      
      return true;
    })
    .slice(0, 50); // Limit to 50 properties max for performance

  if (similar.length === 0) return 50; // No similar properties to compare

  // Calculate average price of similar properties (convert Decimal to number)
  const avgPrice = similar.reduce((sum, p) => {
    const pPrice = toNumber(p.price) || 0;
    return sum + pPrice;
  }, 0) / similar.length;
  const priceRatio = propertyPrice / avgPrice;

  // Score based on how competitive the price is
  // Lower than average = more competitive = higher score
  if (priceRatio < 0.9) return 100; // 10%+ below average = excellent
  if (priceRatio < 0.95) return 90;  // 5-10% below = very good
  if (priceRatio < 1.0) return 80;   // 0-5% below = good
  if (priceRatio < 1.05) return 70; // 0-5% above = fair
  if (priceRatio < 1.1) return 60;  // 5-10% above = okay
  if (priceRatio < 1.2) return 50;  // 10-20% above = neutral
  return 40; // 20%+ above = less competitive
}

/**
 * Calculate location popularity score (0-100)
 * Properties in popular areas (more listings) get higher scores
 */
function calculateLocationPopularityScore(
  property: PropertyWithRelations,
  locationStats: Map<string, number> // Map of "city" or "city:subCity" -> property count
): number {
  if (!property.city) return 50; // Neutral if no location

  const key = property.subCity ? `${property.city}:${property.subCity}` : property.city;
  const count = locationStats.get(key) || 0;

  // More properties in area = more popular = higher score
  // Use logarithmic scaling
  if (count >= 100) return 100;      // Very popular area
  if (count >= 50) return 90;        // Popular area
  if (count >= 25) return 80;        // Moderately popular
  if (count >= 10) return 70;        // Somewhat popular
  if (count >= 5) return 60;         // Less popular
  if (count >= 2) return 50;         // Neutral
  return 40;                          // Less popular area
}

/**
 * Calculate comprehensive property score using multi-factor algorithm
 * 
 * Scoring weights:
 * - Featured Boost: 25%
 * - Engagement Score: 20%
 * - Recency Score: 18%
 * - Agent Boost: 12%
 * - Quality Score: 10%
 * - Price Competitiveness: 8%
 * - Location Popularity: 7%
 */
export async function calculatePropertyScore(
  property: PropertyWithRelations,
  now: Date = new Date(),
  cachedSubscription?: any,
  similarProperties: PropertyWithRelations[] = [],
  locationStats: Map<string, number> = new Map()
): Promise<PropertyScore> {
  const featuredBoost = calculateFeaturedBoost(property, now);
  const engagementScore = calculateEngagementScore(property);
  const recencyScore = calculateRecencyScore(property, now);
  const agentBoost = await calculateAgentBoost(property.owner, cachedSubscription);
  const qualityScore = calculateQualityScore(property, property.owner);
  const priceCompetitivenessScore = calculatePriceCompetitivenessScore(property, similarProperties);
  const locationPopularityScore = calculateLocationPopularityScore(property, locationStats);

  // Weighted final score (adjusted weights to accommodate new factors)
  const finalScore =
    featuredBoost * 0.25 +
    engagementScore * 0.20 +
    recencyScore * 0.18 +
    agentBoost * 0.12 +
    qualityScore * 0.10 +
    priceCompetitivenessScore * 0.08 +
    locationPopularityScore * 0.07;

  return {
    finalScore: Math.round(finalScore * 100) / 100,
    featuredBoost: Math.round(featuredBoost * 100) / 100,
    engagementScore: Math.round(engagementScore * 100) / 100,
    recencyScore: Math.round(recencyScore * 100) / 100,
    agentBoost: Math.round(agentBoost * 100) / 100,
    qualityScore: Math.round(qualityScore * 100) / 100,
    priceCompetitivenessScore: Math.round(priceCompetitivenessScore * 100) / 100,
    locationPopularityScore: Math.round(locationPopularityScore * 100) / 100,
  };
}

/**
 * Batch calculate scores for multiple properties (optimized)
 * Fetches agent subscriptions in batch to avoid N+1 queries
 * Calculates location stats and similar properties for enhanced scoring
 */
export async function calculatePropertyScoresBatch(
  properties: PropertyWithRelations[],
  now: Date = new Date()
): Promise<Map<string, PropertyScore>> {
  // CRITICAL SAFEGUARD: Prevent CPU spike by limiting batch size
  // If too many properties, only score the first batch (shouldn't happen with route limit)
  const MAX_BATCH_SIZE = 200; // Reduced from 500 for better performance
  if (properties.length > MAX_BATCH_SIZE) {
    console.warn(`[PERFORMANCE] calculatePropertyScoresBatch called with ${properties.length} properties, limiting to ${MAX_BATCH_SIZE}`);
    properties = properties.slice(0, MAX_BATCH_SIZE);
  }
  
  if (properties.length === 0) {
    return new Map();
  }
  
  // Get all unique agent user IDs
  const agentUserIds = properties
    .filter((p) => p.owner?.role === 'AGENT' && p.owner?.id)
    .map((p) => p.owner!.id)
    .filter((id, index, self) => self.indexOf(id) === index); // Unique

  // Batch fetch active subscriptions for all agents
  const activeSubscriptions = await prisma.agentSubscription.findMany({
    where: {
      userId: { in: agentUserIds },
      status: 'ACTIVE',
      endDate: { gt: now },
    },
    include: {
      plan: true,
    },
  });

  // Create map for quick lookup
  const subscriptionMap = new Map(
    activeSubscriptions.map((sub) => [sub.userId, sub])
  );

  // Calculate location popularity stats
  const locationStats = new Map<string, number>();
  for (const property of properties) {
    if (property.city) {
      const key = property.subCity ? `${property.city}:${property.subCity}` : property.city;
      locationStats.set(key, (locationStats.get(key) || 0) + 1);
    }
  }

  // CRITICAL FIX: Pre-group similar properties by type/listingType to avoid O(n²) filtering
  // This reduces complexity from O(n²) to O(n)
  const similarPropertiesMap = new Map<string, PropertyWithRelations[]>();
  for (const property of properties) {
    const key = `${property.propertyType || 'UNKNOWN'}:${property.listingType || 'UNKNOWN'}`;
    if (!similarPropertiesMap.has(key)) {
      similarPropertiesMap.set(key, []);
    }
    similarPropertiesMap.get(key)!.push(property);
  }

  // Calculate scores (using cached subscriptions and location stats)
  const scoreMap = new Map<string, PropertyScore>();

  for (const property of properties) {
    const cachedSubscription = property.owner
      ? subscriptionMap.get(property.owner.id) || null
      : null;

    // Get similar properties from pre-grouped map (O(1) lookup instead of O(n) filter)
    const key = `${property.propertyType || 'UNKNOWN'}:${property.listingType || 'UNKNOWN'}`;
    const similarPropertiesGroup = similarPropertiesMap.get(key) || [];
    // Exclude current property and limit to reasonable number for performance
    const similarProperties = similarPropertiesGroup
      .filter((p) => p.id !== property.id)
      .slice(0, 50); // Reduced from 100 to 50 for better performance

    // Calculate score with cached subscription, similar properties, and location stats
    const score = await calculatePropertyScore(
      property,
      now,
      cachedSubscription,
      similarProperties,
      locationStats
    );
    scoreMap.set(property.id, score);
  }

  return scoreMap;
}

