using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Pgo.Backend.Clients;
using Pgo.Backend.Config;
using Pgo.Backend.Models;

namespace Pgo.Backend.Controllers;

//[BffApi]
[Authorize]
[ApiController]
public class FrontendResourcesController(ILogger<FrontendResourcesController> logger, IOptions<PgoConfig> pgoConfig, IFhirClientPgo fhirLocalPgo) : ControllerBase
{
    private readonly ILogger<FrontendResourcesController> _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));

    /// <summary>
    /// Fetch a set of resources for currrent logged-in Patient user. As an example,
    /// we have these stored in a FHIR server. Some PGOs have different store mechanisms.
    /// </summary>
    [HttpGet("api/resources/dossier")] // https://localhost:5001/api/resources/dossier
    public async Task<ActionResult> GetPatientResources()
    {
        var patientId = User.FindFirst("sub")?.Value ?? "";
        //var patientId = "voorbeeldgebruiker";
        var resources = await _fhir.GetPatientResources(patientId);
        var dossier = DossierResponse.Map(resources);

        foreach (var entry in resources)
        {
            _logger.LogInformation($"{entry.TypeName}: {entry.Id}");
        }

        return Ok(dossier);
    }

    /// <summary>
    /// Simple example to have a frontend user download a web page converted to PDF. In <see cref="RemoteResourcesController"/> 
    /// you see a similar endpoint for remote PGO's fetching the PDF, including a waiting time and asynchrononous status polling.
    /// </summary>
    [HttpGet("api/resources/downloaden_als_pdf")] // https://localhost:5001/api/resources/downloaden_als_pdf
    public async Task<ActionResult> DownloadGeneratedPdf()
    {
        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)
        {
            var pdfContent = await response.Content.ReadAsByteArrayAsync();
            return File(pdfContent, "application/pdf");
        }
        else
        {
            _logger.LogError($"{nameof(DownloadGeneratedPdf)} failed to generate PDF: {response.ReasonPhrase}");
            return StatusCode((int)response.StatusCode);
        }
    }
}
