package main

import (
	"bytes"
	"fmt"
	"net/http"
	"text/template"
	"time"

	"gitea.dwysokinski.me/twhelp/corev3/internal/adapter"
	"gitea.dwysokinski.me/twhelp/corev3/internal/tw"
	"github.com/urfave/cli/v2"
)

var (
	twSvcFlagUserAgent = &cli.StringFlag{
		Name:    "tw.userAgent",
		Value:   "tribalwarshelp/{{ .AppVersion }}",
		EnvVars: []string{"TW_USER_AGENT"},
	}
	twSvcFlagTimeout = &cli.DurationFlag{
		Name:    "tw.timeout",
		Value:   10 * time.Second, //nolint:gomnd
		EnvVars: []string{"TW_TIMEOUT"},
		Usage:   "https://pkg.go.dev/net/http#Client.Timeout",
	}
	twSvcFlags = []cli.Flag{
		twSvcFlagUserAgent,
		twSvcFlagTimeout,
	}
)

func newTWServiceFromFlags(c *cli.Context) (*adapter.TWHTTP, error) {
	return newTWService(c.App.Version, c.String(twSvcFlagUserAgent.Name), c.Duration(twSvcFlagTimeout.Name))
}

func newTWService(appVersion, userAgent string, timeout time.Duration) (*adapter.TWHTTP, error) {
	t, err := template.New("").Parse(userAgent)
	if err != nil {
		return nil, fmt.Errorf("something went wron while parsing user agent template: %w", err)
	}

	buf := bytes.NewBuffer(nil)

	if err = t.Execute(buf, map[string]any{
		"AppVersion": appVersion,
	}); err != nil {
		return nil, fmt.Errorf("couldn't exec user agent template: %w", err)
	}

	return adapter.NewTWHTTP(tw.NewClient(
		tw.WithHTTPClient(&http.Client{
			Timeout: timeout,
		}),
		tw.WithUserAgent(buf.String()),
	)), nil
}
