package device

import (
	"context"

	"github.com/break/junhong_cmp_fiber/internal/gateway"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
)

// getDeviceIMEI 通过标识符获取设备并验证 IMEI 存在
// 提供统一的设备查找 + IMEI 校验逻辑，供所有 Gateway 代理方法复用
func (s *Service) getDeviceIMEI(ctx context.Context, identifier string) (string, error) {
	device, err := s.deviceStore.GetByIdentifier(ctx, identifier)
	if err != nil {
		return "", errors.New(errors.CodeNotFound, "设备不存在或无权限访问")
	}
	if device.IMEI == "" {
		return "", errors.New(errors.CodeInvalidParam, "该设备未配置 IMEI，无法调用网关接口")
	}
	return device.IMEI, nil
}

// GatewayGetDeviceInfo 通过标识符查询设备网关信息
func (s *Service) GatewayGetDeviceInfo(ctx context.Context, identifier string) (*gateway.DeviceInfoResp, error) {
	imei, err := s.getDeviceIMEI(ctx, identifier)
	if err != nil {
		return nil, err
	}
	return s.gatewayClient.GetDeviceInfo(ctx, &gateway.DeviceInfoReq{
		DeviceID: imei,
	})
}

// GatewayGetSlotInfo 通过标识符查询设备卡槽信息
func (s *Service) GatewayGetSlotInfo(ctx context.Context, identifier string) (*gateway.SlotInfoResp, error) {
	imei, err := s.getDeviceIMEI(ctx, identifier)
	if err != nil {
		return nil, err
	}
	return s.gatewayClient.GetSlotInfo(ctx, &gateway.DeviceInfoReq{
		DeviceID: imei,
	})
}

// GatewaySetSpeedLimit 通过标识符设置设备限速
func (s *Service) GatewaySetSpeedLimit(ctx context.Context, identifier string, req *dto.SetSpeedLimitRequest) error {
	imei, err := s.getDeviceIMEI(ctx, identifier)
	if err != nil {
		return err
	}
	return s.gatewayClient.SetSpeedLimit(ctx, &gateway.SpeedLimitReq{
		DeviceID:   imei,
		SpeedLimit: req.SpeedLimit,
	})
}

// GatewaySetWiFi 通过标识符设置设备 WiFi
func (s *Service) GatewaySetWiFi(ctx context.Context, identifier string, req *dto.SetWiFiRequest) error {
	imei, err := s.getDeviceIMEI(ctx, identifier)
	if err != nil {
		return err
	}
	return s.gatewayClient.SetWiFi(ctx, &gateway.WiFiReq{
		CardNo:   req.CardNo,
		DeviceID: imei,
		SSID:     req.SSID,
		Password: req.Password,
		Enabled:  req.Enabled,
	})
}

// GatewaySwitchCard 通过标识符切换设备使用的卡
func (s *Service) GatewaySwitchCard(ctx context.Context, identifier string, req *dto.SwitchCardRequest) error {
	imei, err := s.getDeviceIMEI(ctx, identifier)
	if err != nil {
		return err
	}
	return s.gatewayClient.SwitchCard(ctx, &gateway.SwitchCardReq{
		CardNo: imei,
		ICCID:  req.TargetICCID,
	})
}

// GatewayRebootDevice 通过标识符重启设备
func (s *Service) GatewayRebootDevice(ctx context.Context, identifier string) error {
	imei, err := s.getDeviceIMEI(ctx, identifier)
	if err != nil {
		return err
	}
	return s.gatewayClient.RebootDevice(ctx, &gateway.DeviceOperationReq{
		DeviceID: imei,
	})
}

// GatewayResetDevice 通过标识符恢复设备出厂设置
func (s *Service) GatewayResetDevice(ctx context.Context, identifier string) error {
	imei, err := s.getDeviceIMEI(ctx, identifier)
	if err != nil {
		return err
	}
	return s.gatewayClient.ResetDevice(ctx, &gateway.DeviceOperationReq{
		DeviceID: imei,
	})
}
