namespace Lumi.Companion.Core;

/// <summary>
/// Canonical transport boundary for every Companion feature that sends
/// credentials or private stream data to Lumi.
/// </summary>
public static class CompanionTransportPolicy
{
    public static bool IsSecureOrigin(Uri uri) =>
        uri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);

    public static bool IsLoopbackHttpOrigin(Uri uri) =>
        uri.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) &&
        uri.IsLoopback;

    public static bool IsSameOrigin(Uri left, Uri right) =>
        left.Scheme.Equals(right.Scheme, StringComparison.OrdinalIgnoreCase) &&
        left.Host.Equals(right.Host, StringComparison.OrdinalIgnoreCase) &&
        left.Port == right.Port;

    public static bool IsPairingExchangeAllowed(Uri exchangeUri, Uri hostUri) =>
        IsSameOrigin(exchangeUri, hostUri) &&
        ((IsSecureOrigin(exchangeUri) && IsSecureOrigin(hostUri)) ||
         (IsLoopbackHttpOrigin(exchangeUri) && IsLoopbackHttpOrigin(hostUri)));

    public static bool IsPairedHostAllowed(Uri hostUri) =>
        IsSecureOrigin(hostUri) || IsLoopbackHttpOrigin(hostUri);

    public static bool IsEndpointAllowed(Uri endpoint, Uri? pairedHost)
    {
        if (IsSecureOrigin(endpoint)) return true;
        return pairedHost is not null &&
               IsLoopbackHttpOrigin(endpoint) &&
               IsLoopbackHttpOrigin(pairedHost) &&
               IsSameOrigin(endpoint, pairedHost);
    }
}
