package main

import (
	"fmt"
	"log/slog"
	"os"
	"path"

	"code.gitea.io/sdk/gitea"
	"git.schreifuchs.ch/lou-taylor/accounting/internal/config"
	"git.schreifuchs.ch/lou-taylor/accounting/internal/email"
	"git.schreifuchs.ch/lou-taylor/accounting/internal/pdf"
	"git.schreifuchs.ch/lou-taylor/accounting/pkg/invoice"
)

func inject() (cfg *config.Config, log *slog.Logger, invoicer *invoice.Service, mailer *email.Service) {
	log = slog.New(slog.NewTextHandler(os.Stdout, nil))

	cfgDir, err := os.UserConfigDir()
	if err != nil {
		log.Error("Unable to load config dir")
		os.Exit(1)
	}

	cfg, err = config.Load(path.Join(cfgDir, "invoicer/config.json"))
	if err != nil {
		log.Error(fmt.Sprintf("Unable to parse config: %v", err))
		os.Exit(1)
	}

	giteaC, err := gitea.NewClient(
		cfg.Gitea.URL,
		gitea.SetToken(cfg.Gitea.Token),
	)
	if err != nil {
		log.Error(fmt.Sprintf("Unable connect to gitea: %v", err))
		os.Exit(2)
	}
	gotenberg, err := pdf.New(cfg.PDF.Hostname)
	if err != nil {
		log.Error(fmt.Sprintf("Unable connect to gotenberg: %v", err))
		os.Exit(3)
	}
	mailer, err = email.New(cfg.Email)
	if err != nil {
		log.Error(fmt.Sprintf("Unable setup mailer: %v", err))
		os.Exit(4)
	}
	invoicer = invoice.New(log, giteaC, gotenberg)

	return cfg, log, invoicer, mailer
}
