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 ListScoutRunPostsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *ListScoutRunPostsLogic) ListScoutRunPosts(req *types.ScoutRunPostsReq) (resp *types.ScoutRunPostsData, 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 posts request")
	}
	if err := validateRunID(req.RunId); err != nil {
		return nil, err
	}
	if err := validateRunPage(req.Page, req.PageSize); err != nil {
		return nil, err
	}
	page, err := l.svcCtx.Scout.ListRunPosts(l.ctx, uid, req.RunId, req.Page, req.PageSize)
	if err != nil {
		return nil, err
	}
	posts := make([]types.ScoutPostPublic, 0, len(page.Items))
	for _, post := range page.Items {
		posts = append(posts, types.ScoutPostFromDomain(post))
	}
	return &types.ScoutRunPostsData{
		Run: types.ScoutRunFromDomain(page.Run), List: posts,
		Pagination: types.PaginationFromDomain(page.Pagination),
	}, nil
}
