package utm

import (
	"context"
	"fmt"

	"apps/backend/internal/middleware"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *CreateUtmLinkLogic) CreateUtmLink(req *types.CreateUtmLinkReq) (*types.UtmLinkPublic, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok || uid <= 0 {
		return nil, fmt.Errorf("unauthorized")
	}
	u, err := l.svcCtx.Growth.CreateUtmLink(l.ctx, uid, req.DestinationUrl, req.OutcomeId, req.Label)
	if err != nil {
		return nil, err
	}
	out := publicView(l.svcCtx.Config, u)
	return &out, nil
}
