using Ayay.SerilogLogs;
using Serilog;

namespace SHH.CameraSdk.HikFeatures;

public class HikRebootProvider : IRebootFeature
{
    private ILogger _sdkLog = Log.ForContext("SourceContext", LogModules.HikVisionSdk);

    private readonly IHikContext _context;

    public HikRebootProvider(IHikContext context)
    {
        _context = context;
    }

    /// <summary>执行异步重启</summary>
    public async Task RebootAsync()
    {
        // 1. 检查登录状态
        int userId = _context.GetUserId();
        if (userId < 0) throw new InvalidOperationException("设备未登录或离线，无法发送重启指令");

        // 2. 执行 SDK 调用
        await Task.Run(() =>
        {
            bool result = HikNativeMethods.NET_DVR_RebootDVR(userId);

            if (!result)
            {
                uint err = HikNativeMethods.NET_DVR_GetLastError();
                _sdkLog.Error("[SDK] Hik 重启指令下发失败. Error: {Error}", err);

                throw new Exception($"重启指令发送失败，错误码: {err}");
            }

            _sdkLog.Information("[SDK] Hik 重启指令下发成功，设备即将断开连接。");
        });
    }
}