package device_import

import (
	"context"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	assetAuditSvc "github.com/break/junhong_cmp_fiber/internal/service/asset_audit"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
)

// AssetAuditService 资产审计服务接口。
type AssetAuditService interface {
	LogOperation(ctx context.Context, log *model.AssetOperationLog)
}

func (s *Service) logDeviceImportAudit(ctx context.Context, p assetAuditSvc.BuildLogParams) {
	if s == nil || s.assetAudit == nil {
		return
	}
	if p.Operator.Type == "" {
		p.Operator = assetAuditSvc.OperatorFromContext(ctx)
	}
	if p.OperationType == "" {
		p.OperationType = constants.AssetAuditOpDeviceImportTaskCreate
	}
	if p.AssetType == "" {
		p.AssetType = constants.AssetTypeDevice
	}
	p.BeforeData, p.AfterData = assetAuditSvc.WrapOperationContent(p.BeforeData, p.AfterData, nil)
	s.assetAudit.LogOperation(ctx, assetAuditSvc.BuildLog(ctx, p))
}

func newDeviceImportAuditParams(
	taskID uint,
	taskNo string,
	req *dto.ImportDeviceRequest,
	resultStatus string,
	err error,
) assetAuditSvc.BuildLogParams {
	afterData := map[string]any{}
	if req != nil {
		afterData["batch_no"] = req.BatchNo
		afterData["file_key"] = req.FileKey
		afterData["realname_policy"] = req.RealnamePolicy
	}
	errorCode, errorMsg := assetAuditSvc.BuildErrorInfo(err)
	return assetAuditSvc.BuildLogParams{
		AssetID:         taskID,
		AssetIdentifier: taskNo,
		OperationDesc:   "创建设备导入任务",
		ResultStatus:    resultStatus,
		ErrorCode:       errorCode,
		ErrorMsg:        errorMsg,
		AfterData:       afterData,
	}
}

func newDeviceBatchAllocationAuditParams(taskID uint, taskNo string, req *dto.CreateDeviceBatchAllocationRequest, resultStatus string, err error) assetAuditSvc.BuildLogParams {
	afterData := map[string]any{}
	if req != nil {
		afterData["file_key"] = req.FileKey
		afterData["operation_type"] = req.OperationType
		afterData["target_id"] = req.TargetID
	}
	errorCode, errorMsg := assetAuditSvc.BuildErrorInfo(err)
	return assetAuditSvc.BuildLogParams{
		AssetID: taskID, AssetIdentifier: taskNo,
		OperationType: constants.AssetAuditOpDeviceBatchTaskCreate,
		OperationDesc: "创建设备CSV批量分配任务", ResultStatus: resultStatus,
		ErrorCode: errorCode, ErrorMsg: errorMsg, AfterData: afterData,
	}
}
