using ZB.MOM.WW.Configuration;

namespace ZB.MOM.WW.ScadaBridge.DeploymentManager;

/// <summary>
/// Validates <see cref="DeploymentManagerOptions"/> at startup. Each timeout is
/// applied as a linked-CTS deadline around a lifecycle command, per-site artifact
/// deployment, or operation-lock acquisition; a zero/negative value makes the
/// deadline fire immediately (or the <see cref="System.Threading.CancellationTokenSource"/>
/// constructor throw), breaking deployments with an opaque failure. Registered
/// with <c>ValidateOnStart()</c> so a bad <c>ScadaBridge:DeploymentManager</c>
/// section fails fast at boot with a clear, key-naming message.
/// </summary>
public sealed class DeploymentManagerOptionsValidator : OptionsValidatorBase<DeploymentManagerOptions>
{
    /// <inheritdoc />
    protected override void Validate(ValidationBuilder builder, DeploymentManagerOptions options)
    {
        builder.RequireThat(options.LifecycleCommandTimeout > TimeSpan.Zero,
            $"ScadaBridge:DeploymentManager:LifecycleCommandTimeout must be a positive duration " +
            $"(was {options.LifecycleCommandTimeout}); it bounds a lifecycle command round-trip.");

        builder.RequireThat(options.ArtifactDeploymentTimeoutPerSite > TimeSpan.Zero,
            $"ScadaBridge:DeploymentManager:ArtifactDeploymentTimeoutPerSite must be a positive duration " +
            $"(was {options.ArtifactDeploymentTimeoutPerSite}); it bounds per-site artifact deployment.");

        builder.RequireThat(options.OperationLockTimeout > TimeSpan.Zero,
            $"ScadaBridge:DeploymentManager:OperationLockTimeout must be a positive duration " +
            $"(was {options.OperationLockTimeout}); it bounds acquiring an instance operation lock.");

        builder.RequireThat(options.SiteDeploymentMaxParallelism > 0,
            $"ScadaBridge:DeploymentManager:SiteDeploymentMaxParallelism must be at least 1 " +
            $"(was {options.SiteDeploymentMaxParallelism}); it is the SemaphoreSlim bound on a bulk " +
            $"site deployment's site round-trips, and a non-positive value would deadlock the fan-out.");

        builder.RequireThat(options.SiteDeploymentTimeoutPerInstance > TimeSpan.Zero,
            $"ScadaBridge:DeploymentManager:SiteDeploymentTimeoutPerInstance must be a positive duration " +
            $"(was {options.SiteDeploymentTimeoutPerInstance}); it bounds each instance's site round-trip " +
            $"inside a bulk site deployment.");

        builder.RequireThat(options.TerminalDeploymentRecordRetention >= TimeSpan.Zero,
            $"ScadaBridge:DeploymentManager:TerminalDeploymentRecordRetention must not be negative " +
            $"(was {options.TerminalDeploymentRecordRetention}); use TimeSpan.Zero to disable purging of " +
            $"terminal deployment records.");
    }
}
