using Hl7.Fhir.Model;
using Task = System.Threading.Tasks.Task;

public class MedicationAdministrationFhirMapper
{
    private readonly FhirReferenceResolver _refs;

    public MedicationAdministrationFhirMapper(FhirReferenceResolver refs) => _refs = refs;

    public async Task<(CreateMedicationAdministrationRequest Request, Guid EncounterId)> ToCreateRequestAsync(
        Hl7.Fhir.Model.MedicationAdministration fhir)
    {
        if (fhir.Context is null)
            throw new FhirMappingException(
                "MedicationAdministration context is required.", "required");

        var encounterId = await _refs.ResolveEncounterReferenceAsync(fhir.Context);

        var drugName = fhir.Medication is CodeableConcept cc
            ? cc.Text ?? cc.Coding?.FirstOrDefault()?.Display ?? "Unknown"
            : "Unknown";

        var dose = fhir.Dosage?.Dose as Quantity;
        var route = fhir.Dosage?.Route?.Text ?? fhir.Dosage?.Route?.Coding?.FirstOrDefault()?.Display ?? "IV";
        var performer = fhir.Performer?.FirstOrDefault()?.Actor?.Display ?? "Unknown";

        var req = new CreateMedicationAdministrationRequest(
            DrugName: drugName,
            Dose: dose?.Value ?? 0m,
            DoseUnit: dose?.Unit ?? "mg",
            Route: route,
            AdministeredAt: fhir.Effective.ToUtcDateTimeOffset(),
            AdministeredBy: performer);

        return (req, encounterId);
    }
}
