using Microsoft.AspNetCore.Components;
using Blazor.Models;
using Blazor.Services;
using Microsoft.Extensions.Localization;

namespace Blazor.Pages.Admins
{
    public partial class AddAdministrator
    {
        private AdministratorModel administratorModel = new();

        [Inject]
        public IStringLocalizer<AddAdministrator> Localizer { get; set; }

        [Inject]
        public required IDataService DataService { get; set; }

        [Inject]
        public required NavigationManager NavigationManager { get; set; }

        [Inject]
        public required ILogger<AddAdministrator> Logger { get; set; }

        private async Task HandleValidSubmit()
        {
            if (administratorModel != null)
            {
                administratorModel.HashPassword(administratorModel.HashedPassword);

                var formData = new List<KeyValuePair<string, string>>();
                formData.Add(new KeyValuePair<string, string>("username", administratorModel.Username));
                formData.Add(new KeyValuePair<string, string>("password", administratorModel.HashedPassword));

                var formContent = new FormUrlEncodedContent(formData);

                string apiUri = API.API_URL + "add/administrator/" + API.TOKEN;

                using (var httpClient = new HttpClient())
                {
                    var response = await httpClient.PostAsync(apiUri, formContent);

                    if (response.IsSuccessStatusCode)
                    {
                        var responseBody = await response.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        var errorResponse = await response.Content.ReadAsStringAsync();
                    }
                }

                Logger.LogInformation("Admin '{administratorsModelName}' added", administratorModel.Username);

                NavigationManager.NavigateTo("administrators");
            }
        }
    }
}
