package logic

import (
	"audio_transcoder/internal/svc"
	"audio_transcoder/internal/types"
	"context"
	"encoding/json"
	"errors"
	"github.com/google/uuid"
	"regexp"

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

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

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

func (l *TranscoderCallbackLogic) TranscoderCallback(req *types.CallbackRequest) (resp *types.CallbackResponse, err error) {
	if req.Path == "" || req.CallbackUrl == "" {
		err = errors.New("path or callback_url is empty")
		return
	}
	//校验req.Path是否符合url的正则格式
	var urlRegexp = regexp.MustCompile(`^(?:(http|https|ftp):\/\/)?((|[\w-]+\.)+[a-z0-9]+)(?:(\/[^/?#]+)*)?(\?[^#]+)?(#.+)?$`)
	if !urlRegexp.MatchString(req.Path) || !urlRegexp.MatchString(req.CallbackUrl) {
		err = errors.New("path or callback_url is not url")
		return
	}
	bts, err := json.Marshal(req)
	if err != nil {
		return
	}
	err = l.svcCtx.BoltSdk.Set(uuid.NewString(), string(bts))
	return
}
