using CityInfo.WEB.Models;
using System.Net.Http.Json;

namespace CityInfo.WEB.Services
{
    public class CityDataService : ICityDataService
    {
        private readonly HttpClient _httpClient;

        public CityDataService(
            HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<City> CreateCity(City city)
        {
            var response = await _httpClient.PostAsJsonAsync<City>("/api/cities", city);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadFromJsonAsync<City>();
            }
            return null;
        }

        public async Task DeleteCity(int cityId)
        {
            await _httpClient.DeleteAsync($"/api/cities/{cityId}");
        }

        public async Task<IEnumerable<City>> GetCities()
        {
            return await _httpClient.GetFromJsonAsync<IEnumerable<City>>("/api/cities");
        }

        public async Task<City> GetCity(int cityId)
        {
            return await _httpClient.GetFromJsonAsync<City>($"/api/cities/{cityId}");
        }

        public async Task UpdateCity(City city)
        {
            await _httpClient.PutAsJsonAsync<City>($"/api/cities/{city.Id}", city);
        }
    }
}
