using Hl7.Fhir.Model;

namespace Pgo.Backend.Helpers;

public static class FhirBundleExtensions
{

    public static Bundle AsDocumentBundle(this Bundle searchsetBundle)
    {
        var patient = searchsetBundle.Entry.FirstOrDefault(e => e.Resource is Patient)?.Resource as Patient;

        var composition = new Composition
        {
            Id = Guid.NewGuid().ToString(),
            Status = CompositionStatus.Final,
            Type = new CodeableConcept("http://loinc.org", "18842-5", "Demo"),
            Subject = patient != null ? new ResourceReference($"Patient/{patient.Id}") : null,
            Date = DateTime.UtcNow.ToString("o"), // Adjusted to string
            Author = new List<ResourceReference> { new ResourceReference("Practitioner/demo1") },
            Title = "Generated Document from Searchset",
            Section = new List<Composition.SectionComponent>()
        };

        // Voorbeeldsectie met conditions.
        var conditions = searchsetBundle.Entry.Where(e => e.Resource is Condition).Select(e => e.Resource as Condition).ToList();
        if (conditions.Any())
        {
            composition.Section.Add(new Composition.SectionComponent
            {
                Title = "Conditions",
                Text = new Narrative { Status = Narrative.NarrativeStatus.Generated, Div = "Markdown-tekst" },
                Entry = conditions.Select(consdition => new ResourceReference($"Condition/{consdition?.Id}")).ToList()
            });
        }
        var documentBundle = new Bundle
        {
            Type = Bundle.BundleType.Document,
            Entry = new List<Bundle.EntryComponent>()
        };

        // Composition als eerrste entry.
        documentBundle.Entry.Add(new Bundle.EntryComponent
        {
            FullUrl = $"urn:uuid:{composition.Id}",
            Resource = composition
        });

        foreach (var entry in searchsetBundle.Entry)
        {
            documentBundle.Entry.Add(new Bundle.EntryComponent
            {
                FullUrl = $"urn:uuid:{entry.Resource.Id}",
                Resource = entry.Resource
            });
        }

        return documentBundle;
    }
}
