package iot_card_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) logIotCardImportAudit(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.AssetAuditOpIotCardImportTaskCreate
	}
	if p.AssetType == "" {
		p.AssetType = constants.AssetTypeIotCard
	}
	p.BeforeData, p.AfterData = assetAuditSvc.WrapOperationContent(p.BeforeData, p.AfterData, nil)
	s.assetAudit.LogOperation(ctx, assetAuditSvc.BuildLog(ctx, p))
}

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