using System.Threading;
using System.Threading.Tasks;
using ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Shared.Contracts;

namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Host.Backend;

/// <summary>
///     Safe default when the deployment hasn't configured a real Fwlib32 backend.
///     Returns structured failure responses instead of throwing so the Proxy can map the
///     error to <c>BadDeviceFailure</c> and surface a clear operator message pointing at
///     <c>docs/v2/focas-deployment.md</c>. Used when <c>OTOPCUA_FOCAS_BACKEND</c> is unset
///     or set to <c>unconfigured</c>.
/// </summary>
public sealed class UnconfiguredFocasBackend : IFocasBackend
{
    private const uint BadDeviceFailure = 0x80550000u;
    private const string Reason =
        "FOCAS Host is running without a real Fwlib32 backend. Set OTOPCUA_FOCAS_BACKEND=fwlib32 " +
        "and ensure Fwlib32.dll is on PATH — see docs/v2/focas-deployment.md.";

    public Task<OpenSessionResponse> OpenSessionAsync(OpenSessionRequest request, CancellationToken ct) =>
        Task.FromResult(new OpenSessionResponse { Success = false, Error = Reason, ErrorCode = "NoFwlibBackend" });

    public Task CloseSessionAsync(CloseSessionRequest request, CancellationToken ct) => Task.CompletedTask;

    public Task<ReadResponse> ReadAsync(ReadRequest request, CancellationToken ct) =>
        Task.FromResult(new ReadResponse { Success = false, StatusCode = BadDeviceFailure, Error = Reason });

    public Task<WriteResponse> WriteAsync(WriteRequest request, CancellationToken ct) =>
        Task.FromResult(new WriteResponse { Success = false, StatusCode = BadDeviceFailure, Error = Reason });

    public Task<PmcBitWriteResponse> PmcBitWriteAsync(PmcBitWriteRequest request, CancellationToken ct) =>
        Task.FromResult(new PmcBitWriteResponse { Success = false, StatusCode = BadDeviceFailure, Error = Reason });

    public Task<ProbeResponse> ProbeAsync(ProbeRequest request, CancellationToken ct) =>
        Task.FromResult(new ProbeResponse { Healthy = false, Error = Reason, ObservedAtUtcUnixMs = System.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
}
