using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Aberwyn.Data
{
    public class MovieMetadataService
    {
        private readonly HttpClient _http;
        private readonly string _apiKey = "6a666b45";
        private readonly string _tpiKey = "6a666b45";


        public MovieMetadataService(HttpClient httpClient)
        {
            _http = httpClient;
        }

        public async Task<MovieMetadata?> GetMovieAsync(string title, int? year = null)
        {
            if (string.IsNullOrWhiteSpace(title))
                return null;

            try
            {
                MovieMetadata? metadata = null;

                // Först försök med titel + år
                if (year.HasValue)
                {
                    var urlWithYear = $"https://www.omdbapi.com/?t={Uri.EscapeDataString(title)}&y={year.Value}&apikey={_apiKey}";
                    metadata = await _http.GetFromJsonAsync<MovieMetadata>(urlWithYear);
                }

                // Om inget hittas, försök bara med titel
                if (metadata == null || string.IsNullOrEmpty(metadata.Title))
                {
                    var urlTitleOnly = $"https://www.omdbapi.com/?t={Uri.EscapeDataString(title)}&apikey={_apiKey}";
                    metadata = await _http.GetFromJsonAsync<MovieMetadata>(urlTitleOnly);
                }

                // Returnera metadata om något hittades
                return (metadata != null && !string.IsNullOrEmpty(metadata.Title)) ? metadata : null;
            }
            catch
            {
                return null;
            }
        }
    }

    public class TmdbService
    {
        private readonly HttpClient _http = new();
        private readonly string _apiKey = "aef2f49296b77b9b9c269678d04bdbc6";
        private readonly string _country = "SE";

        public async Task<string> GetWatchProvidersByTitleAsync(string title, int? year = null)
        {
            var query = Uri.EscapeDataString(title);
            var url = $"https://api.themoviedb.org/3/search/movie?api_key={_apiKey}&query={query}";
            if (year.HasValue)
                url += $"&year={year.Value}";

            var searchResult = await _http.GetFromJsonAsync<TmdbSearchResponse>(url);
            var movie = searchResult?.Results?.FirstOrDefault();
            if (movie == null) return "";

            var providersUrl = $"https://api.themoviedb.org/3/movie/{movie.Id}/watch/providers?api_key={_apiKey}";
            var providersResult = await _http.GetFromJsonAsync<WatchProvidersResponse>(providersUrl);

            if (providersResult?.Results?.ContainsKey(_country) == true)
            {
                var seProviders = providersResult.Results[_country];
                var names = new List<string>();
                if (seProviders.Flatrate != null) names.AddRange(seProviders.Flatrate.Select(p => p.ProviderName));
                //if (seProviders.Rent != null) names.AddRange(seProviders.Rent.Select(p => p.ProviderName));
                //if (seProviders.Buy != null) names.AddRange(seProviders.Buy.Select(p => p.ProviderName));
                return string.Join(", ", names.Distinct());
            }

            return "";
        }
    }

    // JSON-klasser för TMDb
    public class TmdbSearchResponse { public List<TmdbMovie> Results { get; set; } = new(); }
    public class TmdbMovie { public int Id { get; set; } }
    public class WatchProvidersResponse { public Dictionary<string, CountryProviders> Results { get; set; } = new(); }
    public class CountryProviders
    {
        public List<Provider>? Flatrate { get; set; }
        public List<Provider>? Rent { get; set; }
        public List<Provider>? Buy { get; set; }
    }
    public class Provider
    {
        [JsonPropertyName("provider_name")]
        public string ProviderName { get; set; } = "";
    }


}
