using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace Ticket_System
{


    public sealed class AuthApiClient
    {
        private readonly HttpClient _http;
        private readonly JsonSerializerOptions _json = new() { PropertyNameCaseInsensitive = true };

        public AuthApiClient(string baseUrl)
        {
            _http = new HttpClient { BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/") };
        }

        public async Task<ResponseToken?> SignInAsync(string name, string password)
        {
            var req = new SignInRequest { name = name, password = password };

            var content = new StringContent(
                JsonSerializer.Serialize(req),
                Encoding.UTF8,
                "application/json"
            );

            using var resp = await _http.PostAsync("signin", content);
            var body = await resp.Content.ReadAsStringAsync();

            if (resp.IsSuccessStatusCode)
            {
                return JsonSerializer.Deserialize<ResponseToken>(body, _json);
            }

            // optional: Fehler-Body auswerten
            // var err = JsonSerializer.Deserialize<SignInErrorResponse>(body, _json);
            return null;
        }

        public async Task<bool> ValidateTokenAsync(string token)
        {
            using var req = new HttpRequestMessage(HttpMethod.Get, "token/validate");
            req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            using var resp = await _http.SendAsync(req);
            var body = await resp.Content.ReadAsStringAsync();

            if (!resp.IsSuccessStatusCode) return false;

            var result = JsonSerializer.Deserialize<TokenIsValid>(body, _json);
            return result?.is_valid == true;
        }
    }

}
