package publicutm

import (
	"context"
	"net/http"

	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

type UtmRedirectLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	w      http.ResponseWriter
	r      *http.Request
}

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

// SetHTTP allows handler to pass ResponseWriter for 302
func (l *UtmRedirectLogic) SetHTTP(w http.ResponseWriter, r *http.Request) {
	l.w, l.r = w, r
}

func (l *UtmRedirectLogic) UtmRedirect(req *types.UtmRedirectReq) (*types.OkData, error) {
	dest, err := l.svcCtx.Growth.TrackUtmClick(l.ctx, req.Code)
	if err != nil {
		return nil, err
	}
	if l.w != nil {
		http.Redirect(l.w, l.r, dest, http.StatusFound)
		return nil, response.Biz(302, 302000, "redirect")
	}
	return &types.OkData{Ok: true, Message: dest}, nil
}
