namespace ConeCalorimeter.Services;

public sealed record TcpDeviceConnectionOptions(string Host, int Port, byte UnitId)
{
    public const string HostEnvironmentVariable = "CONE_DEVICE_HOST";
    public const string PortEnvironmentVariable = "CONE_DEVICE_PORT";
    public const string UnitIdEnvironmentVariable = "CONE_DEVICE_UNIT_ID";

    public static TcpDeviceConnectionOptions Default { get; } = new("192.168.1.10", 502, 1);

    public static TcpDeviceConnectionOptions FromEnvironment()
    {
        var host = Environment.GetEnvironmentVariable(HostEnvironmentVariable);
        var portText = Environment.GetEnvironmentVariable(PortEnvironmentVariable);
        var unitIdText = Environment.GetEnvironmentVariable(UnitIdEnvironmentVariable);

        var port = int.TryParse(portText, out var parsedPort) && parsedPort is > 0 and <= 65535
            ? parsedPort
            : Default.Port;
        var unitId = byte.TryParse(unitIdText, out var parsedUnitId)
            ? parsedUnitId
            : Default.UnitId;

        return new TcpDeviceConnectionOptions(
            string.IsNullOrWhiteSpace(host) ? Default.Host : host.Trim(),
            port,
            unitId);
    }
}
