using Inspectron.Epson.PrintServer.ConfigurationSources;
using Inspectron.Epson.Queue;
using Microsoft.Extensions.Logging;
using System.Net.Http.Json;

namespace Inspectron.Epson.PrintServer.JobStatusReporters;

public class JamesStatusReporter : IJobStatusReporter
{
    private readonly HttpClient _httpClient;
    private readonly EpsonPrintServiceConfiguration _configuration;
    private readonly ILogger _logger;

    public JamesStatusReporter(HttpClient httpClient, EpsonPrintServiceConfiguration configuration, ILogger logger)
    {
        _httpClient = httpClient;
        _configuration = configuration;
        _logger = logger;
    }

    public async Task ReportStatusAsync(PrintJob job, PrintJobStatus status)
    {
        try
        {
            var url = $"{_configuration.ApiUrl?.TrimEnd('/')}/api/printerServer/job-update";
            using var request = new HttpRequestMessage(HttpMethod.Post, url);
            request.Headers.Add("X-Printer-Server-Key", _configuration.ApiKey);
            request.Content = JsonContent.Create(new
            {
                jobId = job.JobId,
                status = (int)status
            });

            var response = await _httpClient.SendAsync(request);
            response.EnsureSuccessStatusCode();
            var text = await response.Content.ReadAsStringAsync();

        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to report status {Status} for job {JobId}", status, job.JobId);
        }
    }
}
