package receiver

import (
	"github.com/tidbcloud/jiraport/pkg/clients/engineer"
	"github.com/tidbcloud/jiraport/pkg/clients/oncall"
	"github.com/tidbcloud/jiraport/pkg/entity"
)

// firemasterTeam is the oncall-service team whose current on-call engineers are
// paged as the top of the escalation ladder.
const firemasterTeam = "fire_master"

// FiremasterReceiverSelector resolves the "firemaster" receiver to the current
// on-call engineers of the dedicated fire_master team, via the oncall service.
type FiremasterReceiverSelector struct {
	engineerClient engineer.Interface
	oncallClient   oncall.Interface
}

func NewFiremasterReceiverSelector(engineerClient engineer.Interface, oncallClient oncall.Interface) (*FiremasterReceiverSelector, error) {
	return &FiremasterReceiverSelector{engineerClient: engineerClient, oncallClient: oncallClient}, nil
}

func (rs *FiremasterReceiverSelector) SelectReceiver(name string, issue *entity.Issue) ([]Receiver, error) {
	if name != "firemaster" {
		return nil, nil
	}
	if rs.oncallClient == nil {
		return nil, &NoAssigneeError{s: "oncall client not configured for firemaster receiver"}
	}

	emails, err := rs.oncallClient.GetCurrentOnCall(firemasterTeam)
	if err != nil {
		return nil, err
	}
	receivers := resolveEngineers(rs.engineerClient, emails)
	if len(receivers) == 0 {
		return nil, &NoAssigneeError{s: "no firemaster on-call as receiver"}
	}
	return receivers, nil
}
