package googlechat

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"time"

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

// Service implements a Google Chat notification service.
type Service struct {
	standard.Standard

	Config     *Config
	httpClient types.HTTPClient
}

const defaultHTTPTimeout = 10 * time.Second

// ErrUnexpectedStatus indicates an unexpected HTTP status code from the Google Chat API.
var ErrUnexpectedStatus = errors.New("google chat api returned unexpected http status code")

// 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{}

	if s.httpClient == nil {
		s.httpClient = &http.Client{Timeout: defaultHTTPTimeout}
	}

	return s.Config.SetURL(serviceURL)
}

// Send delivers a notification message to Google Chat.
func (s *Service) Send(message string, _ *types.Params) error {
	config := s.Config

	jsonBody, err := json.Marshal(JSON{Text: message})
	if err != nil {
		return fmt.Errorf("marshaling message to JSON: %w", err)
	}

	postURL := getAPIURL(config)
	jsonBuffer := bytes.NewBuffer(jsonBody)

	req, err := http.NewRequestWithContext(
		context.Background(),
		http.MethodPost,
		postURL.String(),
		jsonBuffer,
	)
	if err != nil {
		return fmt.Errorf("creating HTTP request: %w", err)
	}

	req.Header.Set("Content-Type", "application/json")

	resp, err := s.httpClient.Do(req)
	if err != nil {
		return fmt.Errorf("sending notification to Google Chat: %w", err)
	}

	defer func() { _ = resp.Body.Close() }()

	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return fmt.Errorf("%w: %d", ErrUnexpectedStatus, resp.StatusCode)
	}

	return nil
}

// SetHTTPClient sets a custom HTTP client for the service.
func (s *Service) SetHTTPClient(client types.HTTPClient) {
	s.httpClient = client
}

// getAPIURL constructs the service URL for Google Chat notifications.
func getAPIURL(config *Config) *url.URL {
	query := url.Values{}
	query.Set("key", config.Key)
	query.Set("token", config.Token)

	return &url.URL{
		Path:     config.Path,
		Host:     config.Host,
		Scheme:   "https",
		RawQuery: query.Encode(),
	}
}
