package flow

import (
	"regexp"
)

const (
	maskedPlaceholder = "[MASKED]"
)

var (
	// gitlabTokenRegexps from https://gitlab.com/gitlab-org/gitlab/-/blob/53b3640fcd4db2dca135ba2e3d058d144f33d577/app/assets/javascripts/lib/utils/secret_detection_patterns.js#L2
	gitlabTokenRegexps = []*regexp.Regexp{
		// GitLab personal access token (routable)
		regexp.MustCompile(`glpat-(?<base64_payload>[0-9a-zA-Z_-]{27,300})\.(?<base64_payload_length>[0-9a-z]{2})(?<crc32>[0-9a-z]{7})`),
		// GitLab personal access token
		regexp.MustCompile(`glpat-[0-9a-zA-Z_-]{20}`),
		// Feed Token
		regexp.MustCompile(`feed_token=[0-9a-zA-Z_-]{20}|glft-[0-9a-zA-Z_-]{20}|glft-[a-h0-9]+-[0-9]+_`),
		// GitLab OAuth Application Secret
		regexp.MustCompile(`gloas-[0-9a-zA-Z_-]{64}`),
		// GitLab Deploy Token
		regexp.MustCompile(`gldt-[0-9a-zA-Z_-]{20}`),
		// GitLab SCIM OAuth Access Token
		regexp.MustCompile(`glsoat-[0-9a-zA-Z_-]{20}`),
		// GitLab CI Build (Job) Token
		regexp.MustCompile(`glcbt-[0-9a-zA-Z]{1,5}_[0-9a-zA-Z_-]{20}`),
		// GitLab Feature Flags Client Token
		regexp.MustCompile(`glffct-[0-9a-zA-Z_-]{20}`),
		// GitLab Runner Token
		regexp.MustCompile(`glrt-[0-9a-zA-Z_-]{20}`),
		// GitLab Incoming Mail Token
		regexp.MustCompile(`glimt-[0-9a-zA-Z_-]{25}`),
		// GitLab Agent for Kubernetes Token
		regexp.MustCompile(`glagent-[0-9a-zA-Z_-]{50}`),
		// GitLab Pipeline Trigger Token
		regexp.MustCompile(`glptt-[0-9a-zA-Z_-]{40}`),
		// Anthropic key
		regexp.MustCompile(`sk-ant-[a-z]{3}\d{2}-[A-Za-z0-9-_]{86}-[A-Za-z0-9-_]{8}`),
	}
)

func maskSensitiveGitLabValues(msg string) string {
	for _, r := range gitlabTokenRegexps {
		msg = r.ReplaceAllString(msg, maskedPlaceholder)
	}
	return msg
}
