package radar

import (
	"context"

	"apps/backend/internal/logic/radarmap"
	radarDomain "apps/backend/internal/module/radar/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *ListWatchesLogic) ListWatches(req *types.ListWatchesReq) (resp *types.WatchListData, err error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	filter := radarDomain.WatchListFilter{Status: req.Status, ContextMode: req.ContextMode, BrandID: req.BrandId, ProductID: req.ProductId, Page: req.Page, PageSize: req.PageSize}
	list, total, err := l.svcCtx.Radar.ListWatches(l.ctx, uid, filter)
	if err != nil {
		return nil, err
	}
	activeCount, err := l.svcCtx.Radar.CountActiveWatches(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	maxActive, err := l.svcCtx.Radar.MaxActiveWatches(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	// profile_exists 讓雷達頁顯示「服務檔案可之後再補」，不再當硬門檻。
	hasProfile, err := l.svcCtx.Radar.HasServiceProfile(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	return &types.WatchListData{
		List:          radarmap.WatchList(list),
		Pagination:    radarmap.Pagination(req.Page, req.PageSize, total),
		ActiveCount:   int(activeCount),
		MaxActive:     maxActive,
		ProfileExists: hasProfile,
	}, nil
}
