package job

import (
	"context"

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

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

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

func (l *CreateJobLogic) CreateJob(req *types.CreateJobReq) (*types.JobData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	payload := req.Payload
	if payload == nil {
		payload = map[string]any{}
	}
	if _, ok := payload["tenant_id"]; !ok && tenantID != "" {
		payload["tenant_id"] = tenantID
	}
	if _, ok := payload["owner_uid"]; !ok && uid != "" {
		payload["owner_uid"] = uid
	}
	scopeID := req.ScopeID
	if req.Scope == "user" && scopeID == "" {
		scopeID = uid
	}
	run, err := l.svcCtx.Job.CreateRun(l.ctx, domusecase.CreateRunRequest{
		TemplateType: req.TemplateType,
		Scope:        req.Scope,
		ScopeID:      scopeID,
		TenantID:     tenantID,
		OwnerUID:     uid,
		Payload:      payload,
	})
	if err != nil {
		return nil, err
	}
	data := toJobData(run)
	return &data, nil
}
