package utils

import (
	"fmt"
	"net/url"
	"strconv"
	"strings"
)

func ExtractJobId(urlStr string) (int64, error) {
	parsedURL, err := url.Parse(urlStr)

	if err != nil {
		return 0, fmt.Errorf("failed to parse URL: %w", err)
	}

	path := parsedURL.Path
	segments := strings.Split(strings.Trim(path, "/"), "/")

	for i := len(segments) - 1; i >= 0; i-- {
		if segments[i] != "" {
			jobId, err := strconv.ParseInt(segments[i], 10, 64)
			if err == nil {
				return jobId, nil
			}
		}
	}

	return 0, fmt.Errorf("no numeric job ID found in URL path: %s", path)
}
