package teller

import (
	"context"
	_ "embed"
	"fmt"
	"io"
	"net/http"
	"os"
	"slices"
	"text/template"
)

var (
	//go:embed application_id.txt
	applicationId string
	//go:embed init.html
	initHTML string
)

func Init(ctx context.Context) error {
	environment := "development"
	if sandbox := !slices.Contains(os.Args, "forreal"); sandbox {
		environment = "sandbox"
	}
	fmt.Printf("environment=%q\n", environment)

	newTokens := make(chan string)
	defer close(newTokens)
	s := &http.Server{
		Addr: ":20000",
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Method != http.MethodGet {
				b, _ := io.ReadAll(r.Body)
				newTokens <- string(b)
				return
			}

			t, err := template.New("initHTML").Parse(initHTML)
			if err != nil {
				panic(err)
			}

			if err := t.Execute(w, map[string]string{
				"applicationId": applicationId,
				"environment":   environment,
			}); err != nil {
				panic(err)
			}
		}),
	}
	defer s.Close()
	go s.ListenAndServe()

	fmt.Println("Open http://localhost:20000")

	select {
	case <-ctx.Done():
	case newToken := <-newTokens:
		return fmt.Errorf("not impl: %q >> token.txt", newToken)
	}

	return ctx.Err()
}
