using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using PhotoboothUploader.Models;

namespace PhotoboothUploader.Services;

public sealed class PhotoboothConnectClient
{
    private readonly HttpClient _httpClient;
    private readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNameCaseInsensitive = true,
    };

    public PhotoboothConnectClient(string baseUrl)
    {
        _httpClient = new HttpClient
        {
            BaseAddress = new Uri(baseUrl),
        };
    }

    public async Task<PhotoboothConnectResponse> RedeemAsync(string code, CancellationToken cancellationToken = default)
    {
        var response = await _httpClient.PostAsJsonAsync("/api/v1/photobooth/connect", new { code }, cancellationToken);
        var payload = await response.Content.ReadFromJsonAsync<PhotoboothConnectResponse>(_jsonOptions, cancellationToken);

        if (payload is null)
        {
            return new PhotoboothConnectResponse
            {
                Message = response.ReasonPhrase ?? "Verbindung fehlgeschlagen.",
            };
        }

        if (!response.IsSuccessStatusCode)
        {
            return new PhotoboothConnectResponse
            {
                Message = payload.Message ?? "Verbindung fehlgeschlagen.",
            };
        }

        return payload;
    }
}
