using BaseDomain.Results;
using Microsoft.Extensions.Configuration;
using Postall.Domain.Dtos;
using Postall.Domain.Services.Contracts;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Postall.Infra.Services
{
    public class VideoYoutubeService : IVideoYoutubeService
    {
        private readonly IConfiguration _configuration;
        private readonly string _apiKey;

        public VideoYoutubeService(IConfiguration configuration)
        {
            _configuration = configuration;
            _apiKey = _configuration["YouTube:ApiKey"];
        }

        /// <summary>
        /// Busca os detalhes de um vídeo na API do YouTube
        /// </summary>
        public async Task<Result<VideoResponse>> GetVideoDetailsAsync(string videoId)
        {
            try
            {
                var youtubeService = new YouTubeBaseServiceWrapper(_apiKey);

                var videosRequest = youtubeService.Videos.List("snippet,statistics");
                videosRequest.Id = videoId;

                var response = await videosRequest.ExecuteAsync();

                if (response.Items.Count == 0)
                    return Result<VideoResponse>.Failure($"Vídeo não encontrado: {videoId}");

                var video = response.Items[0];
                var snippet = video.Snippet;
                var statistics = video.Statistics;

                return new VideoResponse
                {
                    VideoId = video.Id,
                    ChannelId = snippet.ChannelId,
                    Title = snippet.Title,
                    Description = snippet.Description,
                    ThumbnailUrl = snippet.Thumbnails.Medium?.Url ?? snippet.Thumbnails.Default__.Url,
                    PublishedAt = snippet.PublishedAt.GetValueOrDefault(),
                    ViewCount = statistics.ViewCount.GetValueOrDefault(),
                    LikeCount = statistics.LikeCount.GetValueOrDefault(),
                    DislikeCount = statistics.DislikeCount.GetValueOrDefault(),
                    CommentCount = statistics.CommentCount.GetValueOrDefault()
                };
            }
            catch (Exception ex)
            {
                return Result<VideoResponse>.Failure(ex.Message);
            }
        }

        /// <summary>
        /// Busca vídeos de um canal na API do YouTube
        /// </summary>
        public async Task<Result<List<VideoResponse>>> GetChannelVideosAsync(string channelId, int maxResults = 50)
        {
            try
            {
                var youtubeService = new YouTubeBaseServiceWrapper(_apiKey);

                var searchRequest = youtubeService.Search.List("snippet");
                searchRequest.ChannelId = channelId;
                searchRequest.Type = "video";
                searchRequest.Order = Google.Apis.YouTube.v3.SearchResource.ListRequest.OrderEnum.Date;
                searchRequest.MaxResults = maxResults;

                var searchResponse = await searchRequest.ExecuteAsync();
                var videos = new List<VideoResponse>();

                foreach (var item in searchResponse.Items)
                {
                    // Para cada resultado, obter os detalhes completos do vídeo
                    var videoResult = await GetVideoDetailsAsync(item.Id.VideoId);
                    if (videoResult.IsSuccess)
                    {
                        videos.Add(videoResult.Value);
                    }
                }

                return videos;
            }
            catch (Exception ex)
            {
                return Result<List<VideoResponse>>.Failure(ex.Message);
            }
        }

        /// <summary>
        /// Busca vídeos pelo título ou descrição na API do YouTube
        /// </summary>
        public async Task<Result<List<VideoResponse>>> SearchVideosAsync(string query, int maxResults = 10)
        {
            try
            {
                var youtubeService = new YouTubeBaseServiceWrapper(_apiKey);

                var searchRequest = youtubeService.Search.List("snippet");
                searchRequest.Q = query;
                searchRequest.Type = "video";
                searchRequest.MaxResults = maxResults;

                var searchResponse = await searchRequest.ExecuteAsync();
                var videos = new List<VideoResponse>();

                foreach (var item in searchResponse.Items)
                {
                    // Para cada resultado, obter os detalhes completos do vídeo
                    var videoResult = await GetVideoDetailsAsync(item.Id.VideoId);
                    if (videoResult.IsSuccess)
                    {
                        videos.Add(videoResult.Value);
                    }
                }

                return videos;
            }
            catch (Exception ex)
            {
                return Result<List<VideoResponse>>.Failure(ex.Message);
            }
        }
    }
}