package matrix

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strings"

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

// Service sends notifications via the Matrix protocol.
type Service struct {
	standard.Standard

	Config     *Config
	client     *client
	pkr        format.PropKeyResolver
	httpClient types.HTTPClient
}

// Scheme identifies this service in configuration URLs.
const Scheme = "matrix"

// GetID returns the identifier for this service.
func (s *Service) GetID() string {
	return Scheme
}

// Initialize configures the service with a URL and logger.
func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
	s.SetLogger(logger)
	s.Config = &Config{
		EnumlessConfig: standard.EnumlessConfig{},
		User:           "",
		Password:       "",
		DisableTLS:     false,
		Host:           "",
		Rooms:          nil,
		Title:          "",
	}
	s.pkr = format.NewPropKeyResolver(s.Config)

	if err := s.Config.setURL(&s.pkr, serviceURL); err != nil {
		return err
	}

	if serviceURL.Hostname() != "dummy.com" && serviceURL.Host != "" {
		s.client = newClient(s.Config.Host, s.Config.DisableTLS, logger)
		if s.httpClient != nil {
			switch c := s.httpClient.(type) {
			case *http.Client:
				s.client.httpClient = &DefaultHTTPClient{client: c}
			default:
				s.client.httpClient = s.httpClient
			}
		}

		if s.Config.User != "" {
			return s.client.login(context.Background(), s.Config.User, s.Config.Password)
		}

		s.client.useToken(s.Config.Password)
	}

	return nil
}

// Send delivers a notification message to Matrix rooms.
func (s *Service) Send(message string, params *types.Params) error {
	return s.SendWithContext(context.Background(), message, params)
}

// SendWithContext delivers a notification message to Matrix rooms with the provided context.
func (s *Service) SendWithContext(ctx context.Context, message string, params *types.Params) error {
	if s.client == nil {
		return ErrClientNotInitialized
	}

	// Make a per-call copy of the config to avoid mutating the shared s.Config
	cfg := *s.Config

	if err := s.pkr.UpdateConfigFromParams(&cfg, params); err != nil {
		return fmt.Errorf("updating config from params: %w", err)
	}

	// Create message with title if provided
	fullMessage := createMessage(message, cfg.Title)

	sendErrors := s.client.sendMessage(ctx, fullMessage, cfg.Rooms)
	if len(sendErrors) > 0 {
		for _, err := range sendErrors {
			s.Logf("error sending message: %v", err)
		}

		return fmt.Errorf(
			"%v error(s) sending message, with initial error: %w",
			len(sendErrors),
			sendErrors[0],
		)
	}

	return nil
}

// SetHTTPClient sets a custom HTTP client for the service (propagated to internal client).
func (s *Service) SetHTTPClient(client types.HTTPClient) {
	s.httpClient = client
	if s.client != nil {
		switch c := client.(type) {
		case *http.Client:
			s.client.httpClient = &DefaultHTTPClient{client: c}
		default:
			s.client.httpClient = client
		}
	}
}

// createMessage creates the full message body by prepending the title if provided.
// Format: If title is "Alert" and message is "Hello", output is "Alert\n\nHello".
func createMessage(message, title string) string {
	trimmedTitle := strings.TrimSpace(title)
	if trimmedTitle == "" {
		return message
	}

	return trimmedTitle + "\n\n" + message
}
