package utils

import (
	"errors"
	"regexp"
	"strconv"
)

var (
	orgIDRegexp     = regexp.MustCompile(`/api/v1/orgs/(?P<org_id>\d+)`)
	projectIDRegexp = regexp.MustCompile(`/api/v1/orgs/(?P<org_id>\d+)/projects/(?P<project_id>\d+)`)
	clusterIDRegexp = regexp.MustCompile(
		`/api/v1/orgs/(?P<org_id>\d+)/projects/(?P<project_id>\d+)/clusters/(?P<cluster_id>\d+)`,
	)

	v1betaProjectIDRegexp = regexp.MustCompile(`/api/v1beta/projects/(?P<project_id>\d+)`)
	v1betaCusterIDRegexp  = regexp.MustCompile(`/api/v1beta/projects/(?P<project_id>\d+)/clusters/(?P<cluster_id>\d+)`)
)

func ParseOrgIDFromPath(path string) (uint64, error) {
	if index := orgIDRegexp.SubexpIndex("org_id"); index != -1 {
		res := orgIDRegexp.FindStringSubmatch(path)
		if res != nil {
			orgID, err := strconv.ParseUint(res[index], 10, 64)
			return orgID, err
		}
	}
	return 0, errors.New("org_id not found")
}

func ParseProjIDFromPath(path string) (uint64, error) {
	if index := projectIDRegexp.SubexpIndex("project_id"); index != -1 {
		res := projectIDRegexp.FindStringSubmatch(path)
		if res != nil {
			projectID, err := strconv.ParseUint(res[index], 10, 64)
			return projectID, err
		}
	}

	if index := v1betaProjectIDRegexp.SubexpIndex("project_id"); index != -1 {
		res := v1betaProjectIDRegexp.FindStringSubmatch(path)
		if res != nil {
			projectID, err := strconv.ParseUint(res[index], 10, 64)
			return projectID, err
		}
	}

	return 0, errors.New("project_id not found")
}

func ParseClusterIDFromPath(path string) (uint64, error) {
	if index := clusterIDRegexp.SubexpIndex("cluster_id"); index != -1 {
		res := clusterIDRegexp.FindStringSubmatch(path)
		if res != nil {
			clusterID, err := strconv.ParseUint(res[index], 10, 64)
			return clusterID, err
		}
	}

	if index := v1betaCusterIDRegexp.SubexpIndex("cluster_id"); index != -1 {
		res := v1betaCusterIDRegexp.FindStringSubmatch(path)
		if res != nil {
			clusterID, err := strconv.ParseUint(res[index], 10, 64)
			return clusterID, err
		}
	}

	return 0, errors.New("cluster_id not found")
}
