package sop_node

import (
	"context"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetSopNodeByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetSopNodeByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSopNodeByIdLogic {
	return &GetSopNodeByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetSopNodeByIdLogic) GetSopNodeById(req *types.IDReq) (*types.SopNodeInfoResp, error) {
	data, err := l.svcCtx.DB.SopNode.Get(l.ctx, req.Id)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	var actionMessage []types.Action
	if len(data.ActionMessage) > 0 {
		actionMessage = make([]types.Action, len(data.ActionMessage))
		for i, condition := range data.ActionMessage {
			actionMessage[i] = types.Action{
				Type:    condition.Type,
				Content: condition.Content,
			}
		}
	}

	var actionForward *types.ActionForward
	if data.ActionForward != nil {
		actionForward = &types.ActionForward{}
		actionForward.Wxid = data.ActionForward.Wxid
		if len(data.ActionForward.Action) > 0 {
			forwardAction := make([]types.Action, len(data.ActionForward.Action))
			for i, condition := range data.ActionForward.Action {
				forwardAction[i] = types.Action{
					Type:    condition.Type,
					Content: condition.Content,
				}
			}
			actionForward.Action = forwardAction
		}
	} else {
		actionForward = nil
	}

	return &types.SopNodeInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.SopNodeInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:           &data.Status,
			StageId:          &data.StageID,
			ParentId:         &data.ParentID,
			Name:             &data.Name,
			ConditionType:    &data.ConditionType,
			ConditionList:    data.ConditionList,
			NoReplyCondition: &data.NoReplyCondition,
			NoReplyUnit:      &data.NoReplyUnit,
			ActionMessage:    actionMessage,
			ActionLabelAdd:   data.ActionLabelAdd,
			ActionLabelDel:   data.ActionLabelDel,
			ActionForward:    actionForward,
		},
	}, nil
}
