package portal

import (
	"context"
	"encoding/json"
	"strings"

	"github.com/perfect-panel/server/internal/model/subscribe"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/tool"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
)

type GetSubscriptionLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewGetSubscriptionLogic Get Subscription
func NewGetSubscriptionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSubscriptionLogic {
	return &GetSubscriptionLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetSubscriptionLogic) GetSubscription(req *types.GetSubscriptionRequest) (resp *types.GetSubscriptionResponse, err error) {
	resp = &types.GetSubscriptionResponse{
		List: make([]types.Subscribe, 0),
	}
	// Get the subscription list
	_, data, err := l.svcCtx.SubscribeModel.FilterList(l.ctx, &subscribe.FilterParams{
		Page:            1,
		Size:            9999,
		Show:            true,
		Language:        req.Language,
		DefaultLanguage: true,
	})
	if err != nil {
		l.Errorw("[Site GetSubscription]", logger.Field("err", err.Error()))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get subscription list error: %v", err.Error())
	}
	list := make([]types.Subscribe, len(data))
	for i, item := range data {
		var sub types.Subscribe
		tool.DeepCopy(&sub, item)
		if item.Discount != "" {
			var discount []types.SubscribeDiscount
			_ = json.Unmarshal([]byte(item.Discount), &discount)
			sub.Discount = discount
		}

		// Calculate node count
		nodeIds := tool.StringToInt64Slice(item.Nodes)
		var nodeTags []string
		if item.NodeTags != "" {
			tags := strings.Split(item.NodeTags, ",")
			for _, tag := range tags {
				if strings.TrimSpace(tag) != "" {
					nodeTags = append(nodeTags, strings.TrimSpace(tag))
				}
			}
		}

		nodeCount, err := l.svcCtx.NodeModel.CountNodesByIdsAndTags(l.ctx, nodeIds, nodeTags)
		if err != nil {
			l.Logger.Error("[GetSubscription] count nodes failed: ", logger.Field("error", err.Error()))
			sub.NodeCount = 0
		} else {
			sub.NodeCount = nodeCount
		}

		list[i] = sub
	}
	resp.List = list
	return
}
