using Hl7.Fhir.Rest;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Pgo.Backend.Clients;
using Pgo.Backend.Config;
using Pgo.Backend.Models;
using System.Net.Http.Headers;

namespace Pgo.Backend.Controllers;

[Authorize]
[ApiController]
public class ResourcesController(ILogger<ResourcesController> logger, IHttpClientFactory httpClientFactory, IOptions<PgoConfig> configuration /*IFhirClientPgo fhirLocalPgo*/) : ControllerBase
{
    private readonly ILogger<ResourcesController> _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    private readonly IHttpClientFactory _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
    private readonly PgoConfig _config = configuration.Value ?? throw new ArgumentNullException(nameof(configuration));

    /// <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:5002/api/resources/dossier
    public async Task<ActionResult> GetPatientResources()
    {
        /* var accessToken = HttpContext.Session.GetString("access_token");
        if (string.IsNullOrEmpty(accessToken))
        {
            _logger.LogError("GetPatientResources request unauthorized, accesToken in HttpContext.Session is null or empty");
            return Unauthorized();
        } */

        var patientId = User.FindFirst("sub")?.Value ?? "voorbeeldgebruiker";
        var fhirClient = CreateFhirClient(_config.FhirEndpoint);

        var resources = await fhirClient.GetPatientResources(patientId);
        var dossier = DossierResponse.Map(resources);

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

        return Ok(dossier);
    }

    private FhirClient CreateFhirClient(string fhirBaseEndpoint, string? accessToken = null)
    {
        var httpClient = _httpClientFactory.CreateClient("FhirClient");
        if (!string.IsNullOrEmpty(accessToken))
        {
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        }

        var settings = new FhirClientSettings
        {
            PreferredFormat = ResourceFormat.Json,
            VerifyFhirVersion = false,
            PreferredParameterHandling = SearchParameterHandling.Strict
        };
        return new FhirClient(fhirBaseEndpoint, httpClient, settings);
    }
}
