using System.Net.Http.Json;
using System.Text.Json;
using OrderPROPrint.Models;

namespace OrderPROPrint.Services;

public class PrintApiClient : IDisposable
{
    private readonly HttpClient _httpClient;

    public PrintApiClient(string apiUrl, string apiKey)
    {
        _httpClient = new HttpClient
        {
            BaseAddress = new Uri(apiUrl.TrimEnd('/') + "/"),
            Timeout = TimeSpan.FromSeconds(30)
        };
        _httpClient.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
    }

    public async Task<List<PrintJob>> GetPendingJobsAsync()
    {
        var response = await _httpClient.GetAsync("api/print/jobs/pending");
        response.EnsureSuccessStatusCode();

        var json = await response.Content.ReadAsStringAsync();
        var result = JsonSerializer.Deserialize<PendingJobsResponse>(json);
        return result?.Jobs ?? new List<PrintJob>();
    }

    public async Task<byte[]> DownloadLabelAsync(int jobId)
    {
        var response = await _httpClient.GetAsync($"api/print/jobs/{jobId}/download");
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsByteArrayAsync();
    }

    public async Task<bool> MarkCompleteAsync(int jobId)
    {
        var response = await _httpClient.PostAsync($"api/print/jobs/{jobId}/complete", null);
        return response.IsSuccessStatusCode;
    }

    public async Task<bool> TestConnectionAsync()
    {
        try
        {
            var response = await _httpClient.GetAsync("api/print/jobs/pending");
            return response.IsSuccessStatusCode;
        }
        catch
        {
            return false;
        }
    }

    public void Dispose()
    {
        _httpClient.Dispose();
    }
}
