using DbFirst.Contracts.Layouts;

namespace DbFirst.BlazorWebApp.Services;

public class LayoutApiClient : ILayoutApiClient
{
    private readonly HttpClient _httpClient;
    private const string Endpoint = "api/layouts";

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

    public async Task<LayoutDto?> GetAsync(string layoutType, string layoutKey, string userName, CancellationToken ct = default)
    {
        var url = $"{Endpoint}?layoutType={Uri.EscapeDataString(layoutType)}&layoutKey={Uri.EscapeDataString(layoutKey)}&userName={Uri.EscapeDataString(userName)}";
        var response = await _httpClient.GetAsync(url, ct);
        if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            return null;
        }

        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<LayoutDto>();
    }

    public async Task<LayoutDto> UpsertAsync(LayoutDto dto, CancellationToken ct = default)
    {
        var response = await _httpClient.PostAsJsonAsync(Endpoint, dto, ct);
        if (!response.IsSuccessStatusCode)
        {
            var detail = await ApiClientHelper.ReadErrorAsync(response);
            throw new InvalidOperationException(detail);
        }

        var payload = await response.Content.ReadFromJsonAsync<LayoutDto>();
        return payload ?? dto;
    }

    public async Task DeleteAsync(string layoutType, string layoutKey, string userName, CancellationToken ct = default)
    {
        var url = $"{Endpoint}?layoutType={Uri.EscapeDataString(layoutType)}&layoutKey={Uri.EscapeDataString(layoutKey)}&userName={Uri.EscapeDataString(userName)}";
        var response = await _httpClient.DeleteAsync(url, ct);
        if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            return;
        }

        response.EnsureSuccessStatusCode();
    }
}
