package action

import (
	"strings"

	"github.com/tidbcloud/jiraport/pkg/entity"
)

// The cutover gate: who answers this alert.
//
// alertstore is taking over alert response rule by rule. For a rule it owns it
// pages and posts to the Lark group itself, and files the Jira issue only to
// keep the existing Jira consumers working — and that issue still reaches
// jiraport through the Jira webhook. Without this gate a handed-over alert is
// assigned and paged twice.

// alertstoreHandoverLabel is the alert rule label that hands a rule's response
// to alertstore. Deliberately not configurable and deliberately the same name
// jiralert and alertstore hardcode: a name that disagreed between them would
// mean an alert answered twice or not at all, decided by a typo.
const alertstoreHandoverLabel = "response_class"

// commandsSuppressedByHandover are the commands alertstore performs itself.
// Everything else still runs: backfill, report and comment enrich the issue,
// which alertstore does not do and is why the issue is still being filed.
var commandsSuppressedByHandover = map[string]struct{}{
	"notify":   {}, // Lark group cards and urgent/sms/phone to a person
	"assign":   {},
	"escalate": {},
	"custom":   {}, // L2 SEE assignment
}

// suppressedByHandover reports whether cmd must not run because alertstore, not
// jiraport, answers this issue's alert.
func suppressedByHandover(issue *entity.Issue, cmd []string) bool {
	if len(cmd) == 0 {
		return false
	}
	if _, ok := commandsSuppressedByHandover[cmd[0]]; !ok {
		return false
	}
	return handedOverToAlertstore(issue)
}

// handedOverToAlertstore reports whether the alert rule behind this issue says
// alertstore owns the response. It reads the rule, not who filed the issue, so
// it also covers jiralert's fallback of ticketing a handed-over rule when
// forwarding is not configured.
//
// The label's value is alertstore's response tier (page / ticket / logging), so
// presence is the signal; a falsy value rolls one rule back without deleting the
// label. Kept identical to jiralert's canaryLabelMeansHandover — if the two
// disagree about a rule, one alert is answered by both systems.
func handedOverToAlertstore(issue *entity.Issue) bool {
	if issue == nil {
		return false
	}
	value, ok := issue.AlertLabel(alertstoreHandoverLabel)
	if !ok {
		return false
	}
	switch strings.ToLower(strings.TrimSpace(value)) {
	case "false", "0", "no", "off":
		return false
	default:
		return true
	}
}
