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
	}
	return &types.UtmLinkPublic{
		Id: u.ID, Code: u.Code, TrackPath: "/api/v1/public/u/" + u.Code,
		DestinationUrl: u.DestinationURL, OutcomeId: u.OutcomeID, Label: u.Label,
		Clicks: u.Clicks, CreatedAt: u.CreatedAt,
	}, nil
}
