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"
)

// 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:""`
}

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

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

	return c.getURL(&resolver)
}

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

	return c.setURL(&resolver, serviceURL)
}

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

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

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

	if serviceURL.String() != "slack://dummy@dummy.com" {
		if err := c.Token.SetFromProp(token); err != nil {
			return err
		}
	} else {
		c.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
}
