package radar

import (
	"context"

	"apps/backend/internal/logic/radarmap"
	radarUC "apps/backend/internal/module/radar/usecase"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *UpdateWatchLogic) UpdateWatch(req *types.UpdateWatchReq) (resp *types.RadarWatchPublic, err error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	/*
		欄位缺席（nil）＝不動，送 [] ＝清空。差別很重要：只想改地區的請求不該
		把關鍵字一起清掉，而想清掉排除詞的人也得有辦法表達。
	*/
	patch := radarUC.WatchPatch{}
	if req.Terms != nil {
		patch.Terms = &req.Terms
	}
	if req.ExcludeTerms != nil {
		patch.ExcludeTerms = &req.ExcludeTerms
	}
	if req.Regions != nil {
		patch.Regions = &req.Regions
	}
	w, err := l.svcCtx.Radar.UpdateWatch(l.ctx, uid, req.Id, patch)
	if err != nil {
		return nil, err
	}
	return radarmap.Watch(w), nil
}
