package job

import (
	"context"

	domusecase "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *CancelJobLogic) CancelJob(req *types.CancelJobReq) (*types.JobData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	existing, err := l.svcCtx.Job.GetRun(l.ctx, req.ID)
	if err != nil {
		return nil, err
	}
	if err := ensureRunAccess(existing, tenantID, uid); err != nil {
		return nil, err
	}
	run, err := l.svcCtx.Job.RequestCancel(l.ctx, domusecase.CancelRunRequest{
		JobID:  req.ID,
		Reason: req.Reason,
	})
	if err != nil {
		return nil, err
	}
	data := toJobData(run)
	return &data, nil
}
