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; } /// /// Obtém o ID do usuário atual a partir das claims /// 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; } /// /// Obtém a lista de canais que o usuário tem permissão para listar /// public async Task>> GetUserChannelsAsync() { var userId = GetCurrentUserId(); if (string.IsNullOrEmpty(userId)) return new List(); var channelList = await _channelRepository.GetByUserIdAsync(userId); if (!channelList.Any()) { var defaultChannels = new List { 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(); } /// /// Adiciona um canal à lista do usuário /// public async Task> 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); var data = channelDetails.Value.ToChannelData(); data.ChannelId = channelId; data.UserId = userId; data.YoutubeId = channelId; await _channelRepository.AddAsync(data); return true; } catch (Exception ex) { Console.WriteLine($"Erro ao adicionar canal {channelId}: {ex.Message}"); return false; } } /// /// Remove um canal da lista do usuário /// public async Task> 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; } /// /// Busca os detalhes de um canal na API do YouTube /// public async Task> GetChannelDetailsAsync(string channelId) { var channel = await _channelYoutubeService.GetChannelDetailsAsync(channelId); return channel; } /// /// Busca um canal pelo nome ou ID /// public async Task>> SearchChannelsAsync(string query, int maxResults = 5) { if (string.IsNullOrEmpty(query) || query.Length < 3) return new List(); var results = await _channelYoutubeService.SearchChannelsAsync(query, maxResults); return results; } } }