import { Injectable } from '@nestjs/common';
import { ChannelsService } from '../channels/channels.service';
import { MoviesService } from '../movies/movies.service';
import { SeriesService } from '../series/series.service';

export interface SearchResult {
  channels: any[];
  movies: any[];
  series: any[];
}

@Injectable()
export class SearchService {
  constructor(
    private readonly channelsService: ChannelsService,
    private readonly moviesService: MoviesService,
    private readonly seriesService: SeriesService,
  ) {}

  async search(query: string, type: string = 'all'): Promise<SearchResult> {
    const result: SearchResult = {
      channels: [],
      movies: [],
      series: [],
    };

    if (!query || query.trim().length === 0) {
      return result;
    }

    const searchPromises: Promise<void>[] = [];

    if (type === 'all' || type === 'channel') {
      searchPromises.push(
        this.channelsService.search(query).then((channels) => {
          result.channels = channels;
        }),
      );
    }

    if (type === 'all' || type === 'movie') {
      searchPromises.push(
        this.moviesService.search(query).then((movies) => {
          result.movies = movies;
        }),
      );
    }

    if (type === 'all' || type === 'series') {
      searchPromises.push(
        this.seriesService.search(query).then((series) => {
          result.series = series;
        }),
      );
    }

    await Promise.all(searchPromises);

    return result;
  }
}
