package scout

import (
	"context"

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

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

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

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

func (l *ListScoutRunsLogic) ListScoutRuns(req *types.ScoutRunListReq) (resp *types.ScoutRunListData, err error) {
	if l.svcCtx.Scout == nil {
		return nil, response.Biz(503, 503001, "scout not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	if req == nil {
		return nil, response.Biz(400, 400020, "invalid run list request")
	}
	if err := validateRunPage(req.Page, req.PageSize); err != nil {
		return nil, err
	}
	page, err := l.svcCtx.Scout.ListRuns(l.ctx, uid, req.BrandId, req.Mode, req.Page, req.PageSize)
	if err != nil {
		return nil, err
	}
	out := make([]types.ScoutRunPublic, 0, len(page.Items))
	for _, run := range page.Items {
		out = append(out, types.ScoutRunFromDomain(run))
	}
	return &types.ScoutRunListData{List: out, Pagination: types.PaginationFromDomain(page.Pagination)}, nil
}
