import { Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { UniversityLogosEntity } from 'src/entities/UniversityLogos.entity';

/**
 * LandingPagesService - Service for managing landing page-specific content
 *
 * This service handles business logic for retrieving and caching
 * content specific to landing pages, currently focused on university/partner
 * logos but designed to be extensible for other landing page components.
 *
 * Features:
 * - Comprehensive caching with parameter-based cache keys
 * - Dynamic query building with optional filters
 * - Optimized for high-performance landing page delivery
 * - TypeORM repository pattern for database operations
 *
 * Caching Strategy:
 * - Cache keys constructed from query parameters (pageType, countryId)
 * - Cache TTL should be configured in CacheModule
 * - Manual cache invalidation needed when logos are updated
 *
 * @example
 * // Get all active university logos
 * const logos = await landingPagesService.getAllUniversityLogosShortActiveFrontend();
 *
 * @example
 * // Get country-specific logos for student visa page
 * const ukLogos = await landingPagesService.getAllUniversityLogosShortActiveFrontend(
 *   'student_visa',
 *   44
 * );
 */
@Injectable()
export class LandingPagesService {
  constructor(
    private datasource: DataSource,
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
    @InjectRepository(UniversityLogosEntity)
    private readonly universityLogoRepository: Repository<UniversityLogosEntity>,
  ) {}

  /**
   * Get all active university/partner logos
   *
   * Retrieves logos of universities, partners, or associated institutions
   * for display on landing pages. Supports filtering by page context
   * and country-specific content.
   *
   * Performance optimizations:
   * - Uses caching with parameter-based keys
   * - Selects only necessary fields (image, title)
   * - Orders by creation date for consistent display
   *
   * @param pageType - The specific landing page type (e.g., 'student_visa', 'work_permit')
   * @param visaProductCountryId - Optional country ID for country-specific logos
   * @returns Array of university logo entities with selected fields
   *
   * @note Only 'image' and 'title' fields are selected for performance
   * @note Results are ordered by creation date (newest first)
   *
   * @example Return format:
   * [
   *   { image: 'logo1.png', title: 'University of Example' },
   *   { image: 'logo2.png', title: 'Partner Institution' }
   * ]
   */
  async getAllUniversityLogosShortActiveFrontend(
    pageType?: string,
    visaProductCountryId?: number,
  ): Promise<UniversityLogosEntity[]> {
    // Construct cache key from parameters
    const cacheKey = `university_logos:${pageType ?? 'all'}:${visaProductCountryId ?? 'all'}`;

    // Check cache first
    const cachedData =
      await this.cacheManager.get<UniversityLogosEntity[]>(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    // Build query with performance optimizations
    const query = this.universityLogoRepository
      .createQueryBuilder('ul')
      .select(['ul.image', 'ul.title']) // Select only needed fields
      .where('ul.active = :active', { active: '1' });

    // Apply page type filter if provided
    if (pageType) {
      query.andWhere('ul.pagetype = :pageType', { pageType });
    }

    // Apply country filter if provided and valid
    const vpcId = Number(visaProductCountryId);
    if (vpcId && vpcId !== 0) {
      query.andWhere('ul.visa_product_country_id = :visaProductCountryId', {
        visaProductCountryId,
      });
    }

    // Order by creation date (newest first)
    query.orderBy('ul.created', 'DESC');

    // Execute query
    const result = await query.getMany();

    // Cache the result for future requests
    await this.cacheManager.set(cacheKey, result);

    return result;
  }

  // Future service methods that could be added:

  /**
   * Example: Get landing page hero banners
   * async getLandingPageBanners(pageType?: string, countryId?: number) {
   *   // Similar pattern with caching and filtering
   * }
   *
   * Example: Get landing page statistics/KPIs
   * async getLandingPageStats(pageType?: string) {
   *   // Return conversion rates, success metrics, etc.
   * }
   *
   * Example: Get landing page testimonials
   * async getLandingTestimonials(pageType?: string, countryId?: number) {
   *   // Testimonials specific to landing page context
   * }
   *
   * Example: Invalidate cache when logos are updated
   * async invalidateLogosCache(pageType?: string, countryId?: number) {
   *   const cacheKey = `university_logos:${pageType ?? 'all'}:${countryId ?? 'all'}`;
   *   await this.cacheManager.del(cacheKey);
   * }
   */
}
