using Serilog;
using Ayay.SerilogLogs;

namespace SHH.CameraSdk.DahuaFeatures;

/// <summary>
/// [大华功能组件] 远程重启实现
/// </summary>
public class DahuaRebootProvider : IRebootFeature
{
    private ILogger _sdkLog = Log.ForContext("SourceContext", LogModules.DaHuaSdk);

    private readonly IDahuaContext _context;

    public DahuaRebootProvider(IDahuaContext context)
    {
        _context = context;
    }

    /// <summary>执行异步重启</summary>
    public async Task RebootAsync()
    {
        // 1. 检查登录状态 (参照海康逻辑)
        IntPtr loginId = _context.GetUserId();
        if (loginId == IntPtr.Zero)
            throw new InvalidOperationException("大华设备未登录或句柄失效，无法发送重启指令");

        // 2. 执行 SDK 调用
        await Task.Run(() =>
        {
            bool result = NETClient.ControlDevice(loginId, EM_CtrlType.REBOOT, IntPtr.Zero, 5000);

            if (!result)
            {
                string err = NETClient.GetLastError();
                _sdkLog.Error("[SDK] Dahua 重启指令下发失败. Error: {Error}", err);

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

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