package job

import (
	"context"

	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

type ListJobEventsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListJobEventsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListJobEventsLogic {
	return &ListJobEventsLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *ListJobEventsLogic) ListJobEvents(req *types.ListJobEventsReq) (*types.JobEventListData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	run, err := l.svcCtx.Job.GetRun(l.ctx, req.ID)
	if err != nil {
		return nil, err
	}
	if err := ensureRunAccess(run, tenantID, uid); err != nil {
		return nil, err
	}
	limit := req.Limit
	if limit <= 0 {
		limit = 50
	}
	events, err := l.svcCtx.Job.ListJobEvents(l.ctx, req.ID, limit)
	if err != nil {
		return nil, err
	}
	list := make([]types.JobEventData, 0, len(events))
	for _, event := range events {
		list = append(list, toJobEventData(event))
	}
	return &types.JobEventListData{List: list}, nil
}
