using Hl7.Fhir.Model;
using Hl7.Fhir.Rest;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Pgo.Backend.Clients;
using Pgo.Backend.Config;
using Pgo.Backend.Helpers;
using Pgo.Backend.Models;
using Task = System.Threading.Tasks.Task;

namespace Pgo.Backend.Services;

public interface IDocumentService
{
    Task<byte[]> GetDocumentAsync(DocumentRequest request);
}

public class DocumentService(ILogger<DocumentService> logger, IOptions<PgoConfig> pgoConfig, IFhirClientPgo fhirLocalPgo) : IDocumentService
{
    private readonly ILogger<DocumentService> _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    private readonly PgoConfig _config = pgoConfig?.Value ?? throw new ArgumentNullException(nameof(pgoConfig));
    private readonly IFhirClientPgo _fhir = fhirLocalPgo ?? throw new ArgumentNullException(nameof(fhirLocalPgo));


    public async Task<byte[]> GetDocumentAsync(DocumentRequest request)
    {
        using var content = new MultipartFormDataContent();
        content.Add(new StringContent(_config.DossierOverviewUrl), "url");
        content.Add(new StringContent("PDF/A-1b"), "pdfa");

        var response = await _fhir.HttpClient.PostAsync(_config.DocumentServiceUrl, content);
        if (response.IsSuccessStatusCode)
        {
            // Simulate some additional processing time for fetching, processing and converting content to PDF.
            Task.Delay(8 * 1000).Wait();
            return await response.Content.ReadAsByteArrayAsync();
        }
        else
        {
            throw new HttpRequestException($"{nameof(GetDocumentAsync)} failed to generate PDF: {response.ReasonPhrase}");
        }
    }
}