using Hl7.Fhir.Model;

internal static class FhirMappingHelpers
{
    public static DateTimeOffset? ToUtcDateTimeOffset(this DataType? value)
    {
        return value switch
        {
            FhirDateTime fdt => fdt.ToDateTimeOffset(TimeSpan.Zero),
            Period p when p.StartElement is not null => p.StartElement.ToDateTimeOffset(TimeSpan.Zero),
            Instant i => i.Value,
            _ => null
        };
    }

    public static bool TryParseResourceReference(string? reference, out string resourceType, out string id)
    {
        resourceType = "";
        id = "";

        if (string.IsNullOrWhiteSpace(reference))
            return false;

        var refValue = reference;
        if (Uri.TryCreate(refValue, UriKind.Absolute, out var uri))
            refValue = uri.AbsolutePath.TrimStart('/');

        var slash = refValue.IndexOf('/');
        if (slash <= 0)
            return false;

        resourceType = refValue[..slash];
        id = refValue[(slash + 1)..];

        var historyIdx = id.IndexOf('/');
        if (historyIdx > 0)
            id = id[..historyIdx];

        return !string.IsNullOrWhiteSpace(resourceType) && !string.IsNullOrWhiteSpace(id);
    }
}
