using AzureRestApi.Models.Api;
using Microsoft.Extensions.Logging;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace AzureRestApi.Repositories
{
    public class AzureTagRepository
    {
        private readonly HttpClient _httpClient;
        private readonly AccessTokenRepository _accessTokenRepository;
        private readonly ILogger<AzureTagRepository> _logger;

        public AzureTagRepository(HttpClient httpClient, AccessTokenRepository accessTokenRepository, ILogger<AzureTagRepository> logger)
        {
            _httpClient = httpClient;
            _accessTokenRepository = accessTokenRepository;
            _logger = logger;
        }

        public async Task<bool> SetTag(string scope, string name, string value)
        {
            // PUT https://management.azure.com/{scope}/providers/Microsoft.Resources/tags/default?api-version=2021-04-01
            var result = true;
            var accessToken = await _accessTokenRepository.GetAccessToken();
            var uri = new Uri("https://management.azure.com/" + scope + "/providers/Microsoft.Resources/tags/default?api-version=2021-04-01");

            var tagProperties = new TagProperties();
            tagProperties.properties.tags.Add(name, value);
            var body = JsonSerializer.Serialize(tagProperties);

            HttpRequestMessage request = new(HttpMethod.Put, uri);
            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            request.Content = new StringContent(body, Encoding.UTF8, "application/json");

            var response = await _httpClient.SendAsync(request).ConfigureAwait(false);
            try
            {
                response.EnsureSuccessStatusCode();
                await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
            catch 
            {
                result = false;
            }

            return result;
        }
    }
}
