package job

import (
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/job/domain/entity"
)

func runOwnedBy(run *entity.Run, tenantID, uid string) bool {
	if run == nil || strings.TrimSpace(uid) == "" {
		return false
	}
	ownerUID := strings.TrimSpace(run.OwnerUID)
	runTenantID := strings.TrimSpace(run.TenantID)
	if ownerUID == "" && run.Payload != nil {
		ownerUID = stringFromPayload(run.Payload, "owner_uid")
		runTenantID = stringFromPayload(run.Payload, "tenant_id")
	}
	if ownerUID != "" {
		if ownerUID != uid {
			return false
		}
		if runTenantID != "" && tenantID != "" && runTenantID != tenantID {
			return false
		}
		return true
	}
	return run.Scope == "user" && run.ScopeID == uid
}

func ensureRunAccess(run *entity.Run, tenantID, uid string) error {
	if runOwnedBy(run, tenantID, uid) {
		return nil
	}
	return app.For(code.Job).ResNotFound("job run not found")
}

func stringFromPayload(payload map[string]any, key string) string {
	if payload == nil {
		return ""
	}
	value, ok := payload[key]
	if !ok || value == nil {
		return ""
	}
	text, ok := value.(string)
	if !ok {
		return ""
	}
	return strings.TrimSpace(text)
}
