using BaseDomain.Results;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Postall.Domain;
using Postall.Domain.Dtos;
using Postall.Domain.Entities;
using Postall.Domain.Services.Contracts;
using System.Security.Claims;

namespace Postall.Infra.Services
{
    public class ChannelVideoService: IChannelService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IChannelRepository _channelRepository;
        private readonly IChannelYoutubeService _channelYoutubeService;
        private readonly IConfiguration _configuration;
        private readonly string _apiKey;

        public ChannelVideoService(
                IHttpContextAccessor httpContextAccessor,
                IChannelRepository channelRepository,
                IChannelYoutubeService channelYoutubeService
            )
        {
            _httpContextAccessor = httpContextAccessor;
            this._channelRepository = channelRepository;
            this._channelYoutubeService = channelYoutubeService;
        }

        /// <summary>
        /// Obtém o ID do usuário atual a partir das claims
        /// </summary>
        private string GetCurrentUserId()
        {
            var user = _httpContextAccessor.HttpContext.User;
            var userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            if (string.IsNullOrEmpty(userId))
            {
                var email = user.FindFirst(ClaimTypes.Email)?.Value;
                if (!string.IsNullOrEmpty(email))
                {
                    userId = Convert.ToBase64String(
                        System.Text.Encoding.UTF8.GetBytes(email)
                    ).Replace("/", "_").Replace("+", "-").Replace("=", "");
                }
            }

            return userId;
        }

        /// <summary>
        /// Obtém a lista de canais que o usuário tem permissão para listar
        /// </summary>
        public async Task<Result<List<ChannelResponse>>> GetUserChannelsAsync()
        {
            var userId = GetCurrentUserId();

            if (string.IsNullOrEmpty(userId))
                return new List<ChannelResponse>();

            var channelList = await _channelRepository.GetByUserIdAsync(userId);

            if (!channelList.Any())
            {
                var defaultChannels = new List<ChannelData>
                {
                    new ChannelData { Id = "UC_x5XG1OV2P6uZZ5FSM9Ttw", Title = "Google Developers" },
                    new ChannelData { Id = "UCkw4JCwteGrDHIsyIIKo4tQ", Title = "Google" }
                };

                foreach (var channel in defaultChannels)
                {
                    var channelDetails = await this.GetChannelDetailsAsync(channel.Id);
                    if (channelDetails.IsSuccess)
                    {
                        channelList.Add(channelDetails.Value.ToChannelData());
                    }
                    else
                    { 
                        Console.WriteLine($"Erro ao buscar detalhes do canal {channel.Id}: {channelDetails.Error.Description}");
                        channelList.Add(new ChannelData
                        {
                            Id = channel.Id,
                            Title = channel.Title,
                            ThumbnailUrl = "/images/default-channel-thumb.jpg" // Imagem padrão
                        });
                    }
                }
            }

            return channelList.Select(c => c.ToChannelResponse()).ToList();
        }

        /// <summary>
        /// Adiciona um canal à lista do usuário
        /// </summary>
        public async Task<Result<bool>> AddChannelAsync(string channelId)
        {
            if (string.IsNullOrEmpty(channelId))
                return false;

            var userId = GetCurrentUserId();

            if (string.IsNullOrEmpty(userId))
                return false;

            var channelItem = await _channelRepository.GetByUserIdAndChannelIdAsync(userId, channelId);

            try
            {
                if (channelItem != null)
                    return false;

                var channelDetails = await GetChannelDetailsAsync(channelId);

                await _channelRepository.AddAsync(channelDetails.Value.ToChannelData());

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Erro ao adicionar canal {channelId}: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Remove um canal da lista do usuário
        /// </summary>
        public async Task<Result<bool>> RemoveChannel(string channelId)
        {
            if (string.IsNullOrEmpty(channelId))
                return false;

            var userId = GetCurrentUserId();

            var channelItem = await _channelRepository.GetByUserIdAndChannelIdAsync(userId, channelId);

            if (channelItem == null)
                return false; 

            await _channelRepository.DeleteAsync(channelId);

            return true;
        }

        /// <summary>
        /// Busca os detalhes de um canal na API do YouTube
        /// </summary>
        public async Task<Result<ChannelResponse>> GetChannelDetailsAsync(string channelId)
        {
            var channel = await _channelYoutubeService.GetChannelDetailsAsync(channelId);
            return channel;
        }

        /// <summary>
        /// Busca um canal pelo nome ou ID
        /// </summary>
        public async Task<Result<List<ChannelResponse>>> SearchChannelsAsync(string query, int maxResults = 5)
        {
            if (string.IsNullOrEmpty(query) || query.Length < 3)
                return new List<ChannelResponse>();

            var results = await _channelYoutubeService.SearchChannelsAsync(query, maxResults);

            return results;
        }
    }
}
