All files / src/modules/products/services product-recommendation.service.ts

0% Statements 0/190
0% Branches 0/82
0% Functions 0/42
0% Lines 0/176

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ConfigService } from '@nestjs/config';
import { Cron, CronExpression } from '@nestjs/schedule';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
import { User, UserDocument } from '../../../database/schemas/user.schema';
import { UserInteraction, UserInteractionDocument } from '../../../database/schemas/user-interaction.schema';
import { AIRecommendation, AIRecommendationDocument } from '../../../database/schemas/ai-recommendation.schema';
import { AIService } from '../../ai/services/ai.service';
 
export interface RecommendationRequest {
  userId: string;
  type: 'personal' | 'similar' | 'complementary' | 'trending' | 'seasonal' | 'occasion';
  context?: {
    productId?: string;
    category?: string;
    occasion?: string;
    season?: string;
    budget?: { min: number; max: number };
    style?: string;
  };
  limit?: number;
  excludeOwned?: boolean;
}
 
export interface RecommendationResult {
  recommendations: Array<{
    product: ProductDocument;
    score: number;
    reasoning: string;
    confidence: number;
    tags: string[];
  }>;
  algorithm: string;
  generatedAt: Date;
  expiresAt: Date;
  metadata: {
    totalCandidates: number;
    processingTime: number;
    userProfile: {
      preferences: string[];
      recentActivity: string[];
      purchaseHistory: string[];
    };
  };
}
 
export interface StyleProfile {
  dominantStyles: string[];
  colorPreferences: string[];
  brandAffinities: string[];
  priceRange: { min: number; max: number };
  sizeProfile: Record<string, string>;
  occasionPreferences: string[];
  seasonalTrends: string[];
  bodyType?: string;
  lifestyle: string[];
}
 
@Injectable()
export class ProductRecommendationService {
  private readonly logger = new Logger(ProductRecommendationService.name);
 
  constructor(
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @InjectModel(UserInteraction.name) private userInteractionModel: Model<UserInteractionDocument>,
    @InjectModel(AIRecommendation.name) private aiRecommendationModel: Model<AIRecommendationDocument>,
    private aiService: AIService,
    private configService: ConfigService,
  ) {}
 
  // Generate recommendations every 4 hours for active users
  @Cron(CronExpression.EVERY_4_HOURS)
  async generateBatchRecommendations(): Promise<void> {
    this.logger.log('Starting batch recommendation generation');
    
    try {
      // Get active users from last 7 days
      const activeUsers = await this.userModel.find({
        lastActiveAt: { $gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) },
        isActive: true,
      }).limit(1000); // Process in batches
 
      for (const user of activeUsers) {
        try {
          await this.generatePersonalRecommendations(user._id.toString());
        } catch (error) {
          this.logger.error(`Failed to generate recommendations for user ${user._id}`, error);
        }
      }
 
      this.logger.log(`Batch recommendation generation completed for ${activeUsers.length} users`);
    } catch (error) {
      this.logger.error('Error in batch recommendation generation', error);
    }
  }
 
  async getRecommendations(request: RecommendationRequest): Promise<RecommendationResult> {
    const startTime = Date.now();
 
    try {
      let recommendations: RecommendationResult;
 
      switch (request.type) {
        case 'personal':
          recommendations = await this.getPersonalRecommendations(request);
          break;
        case 'similar':
          recommendations = await this.getSimilarProductRecommendations(request);
          break;
        case 'complementary':
          recommendations = await this.getComplementaryRecommendations(request);
          break;
        case 'trending':
          recommendations = await this.getTrendingRecommendations(request);
          break;
        case 'seasonal':
          recommendations = await this.getSeasonalRecommendations(request);
          break;
        case 'occasion':
          recommendations = await this.getOccasionRecommendations(request);
          break;
        default:
          throw new Error(`Unsupported recommendation type: ${request.type}`);
      }
 
      recommendations.metadata.processingTime = Date.now() - startTime;
 
      // Cache recommendations
      await this.cacheRecommendations(request.userId, request.type, recommendations);
 
      return recommendations;
    } catch (error) {
      this.logger.error('Error generating recommendations', error);
      throw new Error(`Recommendation generation failed: ${error.message}`);
    }
  }
 
  private async getPersonalRecommendations(request: RecommendationRequest): Promise<RecommendationResult> {
    const user = await this.userModel.findById(request.userId);
    Iif (!user) {
      throw new Error('User not found');
    }
 
    // Get user's style profile
    const styleProfile = await this.buildUserStyleProfile(request.userId);
    
    // Get user interactions for collaborative filtering
    const userInteractions = await this.getUserInteractions(request.userId);
    
    // Generate embeddings for user preferences
    const userPreferenceText = this.buildUserPreferenceText(styleProfile, userInteractions);
    const userEmbeddings = await this.aiService.generateEmbeddings({
      text: userPreferenceText,
      model: 'sentence-transformers/all-MiniLM-L6-v2',
    });
 
    // Find similar products using vector search
    const candidateProducts = await this.findSimilarProductsByVector(
      userEmbeddings.embeddings,
      request.limit || 20,
      request.excludeOwned ? await this.getUserOwnedProducts(request.userId) : [],
    );
 
    // Score and rank products
    const scoredRecommendations = await this.scorePersonalRecommendations(
      candidateProducts,
      styleProfile,
      userInteractions,
    );
 
    // Generate AI reasoning for top recommendations
    const finalRecommendations = await this.generateRecommendationReasons(
      scoredRecommendations.slice(0, request.limit || 10),
      styleProfile,
    );
 
    return {
      recommendations: finalRecommendations,
      algorithm: 'personal_ai_hybrid',
      generatedAt: new Date(),
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
      metadata: {
        totalCandidates: candidateProducts.length,
        processingTime: 0, // Will be set by caller
        userProfile: {
          preferences: styleProfile.dominantStyles,
          recentActivity: userInteractions.slice(0, 10).map(i => i.actionType),
          purchaseHistory: userInteractions
            .filter(i => i.actionType === 'purchase')
            .slice(0, 5)
            .map(i => i.targetId?.toString() || ''),
        },
      },
    };
  }
 
  private async getSimilarProductRecommendations(request: RecommendationRequest): Promise<RecommendationResult> {
    Iif (!request.context?.productId) {
      throw new Error('Product ID required for similar product recommendations');
    }
 
    const baseProduct = await this.productModel.findById(request.context.productId);
    Iif (!baseProduct) {
      throw new Error('Base product not found');
    }
 
    // Use product embeddings for similarity search
    Iif (!baseProduct.aiFeatures?.embeddings) {
      throw new Error('Product embeddings not available');
    }
 
    const similarProducts = await this.findSimilarProductsByVector(
      baseProduct.aiFeatures.embeddings,
      request.limit || 10,
      [request.context.productId], // Exclude the base product
    );
 
    const recommendations = similarProducts.map((product, index) => ({
      product,
      score: 1 - (index * 0.1), // Decreasing score
      reasoning: `Similar to ${baseProduct.title} in style, category, and features`,
      confidence: Math.max(0.5, 1 - (index * 0.05)),
      tags: ['similar', 'style-match', baseProduct.category.main],
    }));
 
    return {
      recommendations,
      algorithm: 'vector_similarity',
      generatedAt: new Date(),
      expiresAt: new Date(Date.now() + 12 * 60 * 60 * 1000), // 12 hours
      metadata: {
        totalCandidates: similarProducts.length,
        processingTime: 0,
        userProfile: {
          preferences: [],
          recentActivity: [],
          purchaseHistory: [],
        },
      },
    };
  }
 
  private async getComplementaryRecommendations(request: RecommendationRequest): Promise<RecommendationResult> {
    Iif (!request.context?.productId) {
      throw new Error('Product ID required for complementary recommendations');
    }
 
    const baseProduct = await this.productModel.findById(request.context.productId);
    Iif (!baseProduct) {
      throw new Error('Base product not found');
    }
 
    // Use AI to determine complementary items
    const complementaryQuery = `What items would complement a ${baseProduct.category.main} ${baseProduct.title} from ${baseProduct.brand}? Consider style, color coordination, and occasion appropriateness.`;
    
    const aiResponse = await this.aiService.chat({
      messages: [{ role: 'user', content: complementaryQuery }],
      maxTokens: 200,
      temperature: 0.3,
    });
 
    // Extract complementary categories and styles from AI response
    const complementaryCategories = this.extractCategoriesFromAIResponse(aiResponse.message);
    
    // Find products in complementary categories
    const complementaryProducts = await this.productModel.find({
      'category.main': { $in: complementaryCategories },
      _id: { $ne: baseProduct._id },
      isActive: true,
    }).limit(request.limit || 10);
 
    const recommendations = complementaryProducts.map((product, index) => ({
      product,
      score: 0.9 - (index * 0.05),
      reasoning: `Complements ${baseProduct.title} - ${aiResponse.message.substring(0, 100)}...`,
      confidence: 0.8,
      tags: ['complementary', 'style-coordination', 'ai-suggested'],
    }));
 
    return {
      recommendations,
      algorithm: 'ai_complementary',
      generatedAt: new Date(),
      expiresAt: new Date(Date.now() + 6 * 60 * 60 * 1000), // 6 hours
      metadata: {
        totalCandidates: complementaryProducts.length,
        processingTime: 0,
        userProfile: {
          preferences: [],
          recentActivity: [],
          purchaseHistory: [],
        },
      },
    };
  }
 
  private async getTrendingRecommendations(request: RecommendationRequest): Promise<RecommendationResult> {
    const trendingProducts = await this.productModel.aggregate([
      {
        $match: {
          isActive: true,
          ...(request.context?.category && { 'category.main': request.context.category }),
        },
      },
      {
        $addFields: {
          trendingScore: {
            $add: [
              { $multiply: ['$metrics.views', 0.3] },
              { $multiply: ['$metrics.clicks', 0.3] },
              { $multiply: ['$metrics.conversions', 0.2] },
              { $multiply: ['$metrics.wishlistCount', 0.2] },
            ],
          },
        },
      },
      { $sort: { trendingScore: -1, updatedAt: -1 } },
      { $limit: request.limit || 20 },
    ]);
 
    const recommendations = trendingProducts.map((product, index) => ({
      product,
      score: 1 - (index * 0.02),
      reasoning: 'Currently trending based on user engagement and popularity',
      confidence: 0.9,
      tags: ['trending', 'popular', 'high-engagement'],
    }));
 
    return {
      recommendations,
      algorithm: 'trending_engagement',
      generatedAt: new Date(),
      expiresAt: new Date(Date.now() + 2 * 60 * 60 * 1000), // 2 hours
      metadata: {
        totalCandidates: trendingProducts.length,
        processingTime: 0,
        userProfile: {
          preferences: [],
          recentActivity: [],
          purchaseHistory: [],
        },
      },
    };
  }
 
  private async getSeasonalRecommendations(request: RecommendationRequest): Promise<RecommendationResult> {
    const currentSeason = this.getCurrentSeason();
    const seasonalProducts = await this.productModel.find({
      'aiFeatures.seasonality': currentSeason,
      isActive: true,
      ...(request.context?.category && { 'category.main': request.context.category }),
    }).limit(request.limit || 20);
 
    const recommendations = seasonalProducts.map((product, index) => ({
      product,
      score: 0.95 - (index * 0.03),
      reasoning: `Perfect for ${currentSeason} season - matches current weather and trends`,
      confidence: 0.85,
      tags: ['seasonal', currentSeason.toLowerCase(), 'weather-appropriate'],
    }));
 
    return {
      recommendations,
      algorithm: 'seasonal_matching',
      generatedAt: new Date(),
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
      metadata: {
        totalCandidates: seasonalProducts.length,
        processingTime: 0,
        userProfile: {
          preferences: [],
          recentActivity: [],
          purchaseHistory: [],
        },
      },
    };
  }
 
  private async getOccasionRecommendations(request: RecommendationRequest): Promise<RecommendationResult> {
    Iif (!request.context?.occasion) {
      throw new Error('Occasion required for occasion-based recommendations');
    }
 
    const occasionProducts = await this.productModel.find({
      'aiFeatures.occasions': request.context.occasion,
      isActive: true,
    }).limit(request.limit || 15);
 
    const recommendations = occasionProducts.map((product, index) => ({
      product,
      score: 0.9 - (index * 0.04),
      reasoning: `Ideal for ${request.context!.occasion} occasions - appropriate style and formality level`,
      confidence: 0.8,
      tags: ['occasion-specific', request.context!.occasion, 'appropriate'],
    }));
 
    return {
      recommendations,
      algorithm: 'occasion_matching',
      generatedAt: new Date(),
      expiresAt: new Date(Date.now() + 12 * 60 * 60 * 1000), // 12 hours
      metadata: {
        totalCandidates: occasionProducts.length,
        processingTime: 0,
        userProfile: {
          preferences: [],
          recentActivity: [],
          purchaseHistory: [],
        },
      },
    };
  }
 
  private async buildUserStyleProfile(userId: string): Promise<StyleProfile> {
    const user = await this.userModel.findById(userId);
    const interactions = await this.getUserInteractions(userId, 100);
 
    // Analyze user interactions to build style profile
    const categoryFreq = new Map<string, number>();
    const brandFreq = new Map<string, number>();
    const colorFreq = new Map<string, number>();
    let totalSpent = 0;
    let purchaseCount = 0;
 
    for (const interaction of interactions) {
      // This would be more sophisticated in production
      // analyzing actual product data from interactions
    }
 
    return {
      dominantStyles: user?.preferences?.styles || ['casual', 'modern'],
      colorPreferences: user?.preferences?.colors || ['black', 'white', 'blue'],
      brandAffinities: user?.preferences?.brands || [],
      priceRange: {
        min: user?.preferences?.budgetRange?.min || 0,
        max: user?.preferences?.budgetRange?.max || 1000,
      },
      sizeProfile: {
        clothing: user?.preferences?.sizes?.clothing || 'M',
        shoes: user?.preferences?.sizes?.shoes || '42',
        accessories: user?.preferences?.sizes?.accessories || 'One Size',
      },
      occasionPreferences: ['casual', 'work', 'formal'],
      seasonalTrends: [this.getCurrentSeason()],
      bodyType: user?.measurements?.bodyType,
      lifestyle: ['active', 'professional'],
    };
  }
 
  private async getUserInteractions(userId: string, limit: number = 50): Promise<UserInteractionDocument[]> {
    return this.userInteractionModel
      .find({ userId })
      .sort({ timestamp: -1 })
      .limit(limit)
      .populate('targetId');
  }
 
  private buildUserPreferenceText(profile: StyleProfile, interactions: UserInteractionDocument[]): string {
    const recentCategories = interactions
      .slice(0, 10)
      .map(i => (i.context as any)?.category || '')
      .filter(Boolean)
      .join(', ');
 
    return `User preferences: ${profile.dominantStyles.join(', ')} style, 
            colors: ${profile.colorPreferences.join(', ')}, 
            brands: ${profile.brandAffinities.join(', ')}, 
            recent interests: ${recentCategories}`;
  }
 
  private async findSimilarProductsByVector(
    queryVector: number[],
    limit: number,
    excludeIds: string[] = [],
  ): Promise<ProductDocument[]> {
    const pipeline = [
      {
        $vectorSearch: {
          index: 'product_embeddings_index',
          path: 'aiFeatures.embeddings',
          queryVector: queryVector,
          numCandidates: limit * 3,
          limit: limit * 2,
        },
      },
      {
        $match: {
          _id: { $nin: excludeIds.map(id => id) },
          isActive: true,
        },
      },
      {
        $addFields: {
          similarityScore: { $meta: 'vectorSearchScore' },
        },
      },
      { $limit: limit },
    ];
 
    return this.productModel.aggregate(pipeline as any);
  }
 
  private async scorePersonalRecommendations(
    products: ProductDocument[],
    profile: StyleProfile,
    interactions: UserInteractionDocument[],
  ): Promise<Array<{ product: ProductDocument; score: number }>> {
    return products.map(product => {
      let score = 0.5; // Base score
 
      // Style preference matching
      Iif (product.aiFeatures?.styleVector) {
        score += 0.2;
      }
 
      // Brand affinity
      Iif (profile.brandAffinities.includes(product.brand)) {
        score += 0.15;
      }
 
      // Price range matching
      const productPrice = product.variants[0]?.price.current || 0;
      Iif (productPrice >= profile.priceRange.min && productPrice <= profile.priceRange.max) {
        score += 0.1;
      }
 
      // Category preference
      const categoryInteractions = interactions.filter(i => 
        (i.context as any)?.category === product.category.main
      ).length;
      score += Math.min(categoryInteractions * 0.02, 0.1);
 
      // Rating boost
      Iif (product.metrics?.rating >= 4.0) {
        score += 0.05;
      }
 
      return { product, score: Math.min(score, 1.0) };
    }).sort((a, b) => b.score - a.score);
  }
 
  private async generateRecommendationReasons(
    scoredProducts: Array<{ product: ProductDocument; score: number }>,
    profile: StyleProfile,
  ): Promise<RecommendationResult['recommendations']> {
    const recommendations = [];
 
    for (const { product, score } of scoredProducts) {
      try {
        const reasoningPrompt = `Why would this product be a good recommendation for a user who likes ${profile.dominantStyles.join(', ')} style and ${profile.colorPreferences.join(', ')} colors?
        
        Product: ${product.title}
        Brand: ${product.brand}
        Category: ${product.category.main}
        
        Provide a brief, personalized reason (max 50 words).`;
 
        const aiResponse = await this.aiService.chat({
          messages: [{ role: 'user', content: reasoningPrompt }],
          maxTokens: 80,
          temperature: 0.3,
        });
 
        recommendations.push({
          product,
          score,
          reasoning: aiResponse.message.trim(),
          confidence: score,
          tags: this.generateRecommendationTags(product, profile),
        });
      } catch (error) {
        // Fallback reasoning if AI fails
        recommendations.push({
          product,
          score,
          reasoning: `Matches your ${profile.dominantStyles[0]} style preferences and ${product.category.main} interests`,
          confidence: score * 0.8,
          tags: this.generateRecommendationTags(product, profile),
        });
      }
    }
 
    return recommendations;
  }
 
  private generateRecommendationTags(product: ProductDocument, profile: StyleProfile): string[] {
    const tags = ['personalized'];
 
    Iif (profile.brandAffinities.includes(product.brand)) {
      tags.push('favorite-brand');
    }
 
    Iif (profile.dominantStyles.some(style => 
      product.aiFeatures?.occasions?.includes(style)
    )) {
      tags.push('style-match');
    }
 
    Iif (product.variants[0]?.price.discount > 20) {
      tags.push('great-deal');
    }
 
    Iif (product.metrics?.rating >= 4.5) {
      tags.push('highly-rated');
    }
 
    return tags;
  }
 
  private async getUserOwnedProducts(userId: string): Promise<string[]> {
    const purchases = await this.userInteractionModel.find({
      userId,
      actionType: 'purchase',
    }).distinct('targetId');
 
    return purchases.map(id => id.toString());
  }
 
  private extractCategoriesFromAIResponse(response: string): string[] {
    // Simple extraction - would be more sophisticated in production
    const categories = ['accessories', 'shoes', 'bags', 'jewelry'];
    return categories.filter(cat => 
      response.toLowerCase().includes(cat)
    );
  }
 
  private getCurrentSeason(): string {
    const month = new Date().getMonth();
    Iif (month >= 2 && month <= 4) return 'Spring';
    Iif (month >= 5 && month <= 7) return 'Summer';
    Iif (month >= 8 && month <= 10) return 'Fall';
    return 'Winter';
  }
 
  private async cacheRecommendations(
    userId: string,
    type: string,
    recommendations: RecommendationResult,
  ): Promise<void> {
    try {
      const cacheEntry = new this.aiRecommendationModel({
        userId,
        type,
        algorithm: recommendations.algorithm,
        products: recommendations.recommendations.map(r => ({
          productId: r.product._id,
          score: r.score,
          reasoning: r.reasoning,
          position: recommendations.recommendations.indexOf(r),
        })),
        context: {
          trigger: 'api_request',
          basedOn: [],
          filters: {},
          personalityFactors: [],
        },
        performance: {
          impressions: 0,
          clicks: 0,
          conversions: 0,
          ctr: 0,
          conversionRate: 0,
        },
        expiresAt: recommendations.expiresAt,
        createdAt: new Date(),
        isActive: true,
      });
 
      await cacheEntry.save();
    } catch (error) {
      this.logger.error('Error caching recommendations', error);
    }
  }
 
  async generatePersonalRecommendations(userId: string): Promise<void> {
    try {
      const recommendations = await this.getRecommendations({
        userId,
        type: 'personal',
        limit: 20,
        excludeOwned: true,
      });
 
      this.logger.log(`Generated ${recommendations.recommendations.length} personal recommendations for user ${userId}`);
    } catch (error) {
      this.logger.error(`Error generating personal recommendations for user ${userId}`, error);
    }
  }
 
  async getRecommendationPerformance(userId: string, days: number = 7): Promise<{
    totalRecommendations: number;
    clickThroughRate: number;
    conversionRate: number;
    topPerformingAlgorithms: Array<{ algorithm: string; performance: number }>;
  }> {
    try {
      const dateThreshold = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
      
      const recommendations = await this.aiRecommendationModel.find({
        userId,
        createdAt: { $gte: dateThreshold },
      });
 
      const totalRecommendations = recommendations.length;
      const totalImpressions = recommendations.reduce((sum, r) => sum + r.performance.impressions, 0);
      const totalClicks = recommendations.reduce((sum, r) => sum + r.performance.clicks, 0);
      const totalConversions = recommendations.reduce((sum, r) => sum + r.performance.conversions, 0);
 
      return {
        totalRecommendations,
        clickThroughRate: totalImpressions > 0 ? totalClicks / totalImpressions : 0,
        conversionRate: totalClicks > 0 ? totalConversions / totalClicks : 0,
        topPerformingAlgorithms: [], // Would implement algorithm performance analysis
      };
    } catch (error) {
      this.logger.error('Error getting recommendation performance', error);
      throw error;
    }
  }
}