package slack

import (
	"fmt"
	"net/url"

	"github.com/nicholas-fedor/shoutrrr/pkg/format"
	"github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
	"github.com/nicholas-fedor/shoutrrr/pkg/types"
)

const (
	// Scheme is the identifying part of this service's configuration URL.
	Scheme = "slack"
)

// Config for the slack service.
type Config struct {
	standard.EnumlessConfig
	BotName  string `desc:"Bot name"                                                            key:"botname,username"         optional:"uses bot default"`
	Icon     string `desc:"Use emoji or URL as icon (based on presence of http(s):// prefix)"   key:"icon,icon_emoji,icon_url" optional:""                     default:""`
	Token    Token  `desc:"API Bot token"                                                                                                                                 url:"user,pass"`
	Color    string `desc:"Message left-hand border color"                                      key:"color"                    optional:"default border color"`
	Title    string `desc:"Prepended text above the message"                                    key:"title"                    optional:"omitted"`
	Channel  string `desc:"Channel to send messages to in Cxxxxxxxxxx format"                                                                                             url:"host"`
	ThreadTS string `desc:"ts value of the parent message (to send message as reply in thread)" key:"thread_ts"                optional:""`
}

// GetURL returns a URL representation of it's current field values.
func (config *Config) GetURL() *url.URL {
	resolver := format.NewPropKeyResolver(config)

	return config.getURL(&resolver)
}

// SetURL updates a ServiceConfig from a URL representation of it's field values.
func (config *Config) SetURL(url *url.URL) error {
	resolver := format.NewPropKeyResolver(config)

	return config.setURL(&resolver, url)
}

func (config *Config) getURL(resolver types.ConfigQueryResolver) *url.URL {
	return &url.URL{
		User:       config.Token.UserInfo(),
		Host:       config.Channel,
		Scheme:     Scheme,
		ForceQuery: false,
		RawQuery:   format.BuildQuery(resolver),
	}
}

func (config *Config) setURL(resolver types.ConfigQueryResolver, serviceURL *url.URL) error {
	var token string

	var err error

	if len(serviceURL.Path) > 1 {
		// Reading legacy config URL format
		token = serviceURL.Hostname() + serviceURL.Path
		config.Channel = "webhook"
		config.BotName = serviceURL.User.Username()
	} else {
		token = serviceURL.User.String()
		config.Channel = serviceURL.Hostname()
	}

	if serviceURL.String() != "slack://dummy@dummy.com" {
		if err = config.Token.SetFromProp(token); err != nil {
			return err
		}
	} else {
		config.Token.raw = token // Set raw token without validation
	}

	for key, vals := range serviceURL.Query() {
		if err := resolver.Set(key, vals[0]); err != nil {
			return fmt.Errorf("setting query parameter %q to %q: %w", key, vals[0], err)
		}
	}

	return nil
}

// CreateConfigFromURL to use within the slack service.
func CreateConfigFromURL(serviceURL *url.URL) (*Config, error) {
	config := Config{}
	err := config.SetURL(serviceURL)

	return &config, err
}
