using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using PaklenaBasta.MAUI.Models;

namespace PaklenaBasta.MAUI.Services;

public class ApiService
{
    private readonly HttpClient _client;
    public string? Token { get; private set; }
    public string BaseUrl { get; }

    public ApiService(string baseUrl)
    {
        BaseUrl = baseUrl.TrimEnd('/');
        _client = new HttpClient { BaseAddress = new Uri(BaseUrl) };
    }

    private void SetAuthHeader()
    {
        _client.DefaultRequestHeaders.Authorization = null;
        if (!string.IsNullOrEmpty(Token))
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
    }

    public async Task<LoginResponseDto?> LoginAsync(LoginRequestDto request)
    {
        var json = JsonSerializer.Serialize(request);
        var res = await _client.PostAsync("/api/login", new StringContent(json, Encoding.UTF8, "application/json"));
        if (!res.IsSuccessStatusCode) return null;
        var body = await res.Content.ReadAsStringAsync();
        var login = JsonSerializer.Deserialize<LoginResponseDto>(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
        if (login != null)
        {
            Token = login.Token;
            SetAuthHeader();
        }
        return login;
    }

    public async Task<List<FilmDto>?> GetFilmsAsync()
    {
        SetAuthHeader();
        var res = await _client.GetAsync("/api/filmovi");
        if (!res.IsSuccessStatusCode) return null;
        var body = await res.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<List<FilmDto>>(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
    }

    public async Task<StreamResponseDto?> GetStreamAsync(string id)
    {
        SetAuthHeader();
        var res = await _client.GetAsync($"/api/stream/{id}");
        if (!res.IsSuccessStatusCode) return null;
        var body = await res.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<StreamResponseDto>(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
    }
}
