package job

import (
	"context"

	domrepo "haixun-backend/internal/model/job/domain/repository"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *ListJobsLogic) ListJobs(req *types.ListJobsReq) (*types.JobListData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	runs, total, page, pageSize, totalPages, err := l.svcCtx.Job.ListRuns(l.ctx, domrepo.RunListFilter{
		Scope:    req.Scope,
		ScopeID:  req.ScopeID,
		TenantID: tenantID,
		OwnerUID: uid,
	}, req.Page, req.PageSize)
	if err != nil {
		return nil, err
	}
	list := make([]types.JobData, 0, len(runs))
	for _, run := range runs {
		list = append(list, toJobData(run))
	}
	return &types.JobListData{
		Pagination: types.PaginationData{
			Total:      total,
			Page:       page,
			PageSize:   pageSize,
			TotalPages: totalPages,
		},
		List: list,
	}, nil
}
