package config

import (
	"bytes"
	"encoding/json"
	"net/http"

	"github.com/alecthomas/chroma/v2/formatters/html"
	"github.com/alecthomas/chroma/v2/lexers"
	"github.com/alecthomas/chroma/v2/styles"

	"git.gabrielgio.me/cerrado/pkg/config"
	"git.gabrielgio.me/cerrado/pkg/ext"
	"git.gabrielgio.me/cerrado/templates"
)

type (
	configurationRepository interface {
		GetRootReadme() string
		List() []*config.GitRepositoryConfiguration
	}
)

func ConfigFile(configRepo configurationRepository) ext.ErrorRequestHandler {
	return func(w http.ResponseWriter, _ *http.Request) error {

		config := struct {
			RootReadme   string
			Repositories []*config.GitRepositoryConfiguration
		}{
			RootReadme:   configRepo.GetRootReadme(),
			Repositories: configRepo.List(),
		}

		b, err := json.MarshalIndent(config, "", "  ")
		if err != nil {
			return err
		}

		lexer := lexers.Get("json")
		style := styles.Get("monokailight")
		formatter := html.New(
			html.WithLineNumbers(true),
		)
		iterator, err := lexer.Tokenise(nil, string(b))
		if err != nil {
			return err
		}

		var code bytes.Buffer
		err = formatter.Format(&code, style, iterator)
		if err != nil {
			return err
		}

		hello := &templates.ConfigPage{
			Body: code.Bytes(),
		}

		templates.WritePageTemplate(w, hello)
		return nil
	}
}