package jobs

import (
	"context"

	"apps/backend/internal/middleware"
	jobDomain "apps/backend/internal/module/job/domain"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *ListJobsLogic) ListJobs(req *types.JobListReq) (*types.JobListData, error) {
	if l.svcCtx.Jobs == nil {
		return nil, response.Biz(503, 503001, "jobs module not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	tab := jobDomain.NormalizeListTab(req.Tab)
	page, pageSize := jobDomain.ClampPage(req.Page, req.PageSize)
	list, total, err := l.svcCtx.Jobs.ListTab(l.ctx, uid, tab, page, pageSize)
	if err != nil {
		return nil, err
	}
	out := make([]types.JobPublic, 0, len(list))
	for _, j := range list {
		out = append(out, types.JobFromModel(j))
	}
	totalPages := 0
	if pageSize > 0 {
		totalPages = int((total + int64(pageSize) - 1) / int64(pageSize))
	}
	return &types.JobListData{
		List: out,
		Pagination: types.Pagination{
			Page:       page,
			PageSize:   pageSize,
			Total:      total,
			TotalPages: totalPages,
		},
	}, nil
}
