package main

import (
	"log"
	"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 getConfig() (cfg *config.Config) {
	cfg, err := config.Load("config.json")
	if err == nil {
		return cfg
	}
	cfg, err = config.Load(path.Join(os.Getenv("HOME"), ".config/invoicer/config.json"))
	if err == nil {
		return cfg
	}
	cfg, err = config.Load("/etc/invoicer/config.json")
	if err == nil {
		return cfg
	}

	log.Fatal("no cli config found")
	return cfg
}

func getServices() (invoicer *invoice.Service, mailer *email.Service) {
	cfg := getConfig()

	logr := slog.New(slog.NewTextHandler(os.Stdout, nil))

	giteaC, err := gitea.NewClient(
		cfg.Gitea.URL,
		gitea.SetToken(cfg.Gitea.Token),
	)
	if err != nil {
		log.Fatal("could not connect to gitea: %v", err)
		return invoicer, mailer
	}
	gotenberg, err := pdf.New(cfg.PDF.Hostname)
	if err != nil {
		panic(err)
	}
	if err != nil {
		log.Fatal("could not connect to gotenberg: %v", err)
		return invoicer, mailer
	}
	mailer, err = email.New(cfg.Email)
	if err != nil {
		log.Fatal("could not create mailer: %v", err)
		return invoicer, mailer
	}

	invoicer = invoice.New(logr, giteaC, gotenberg)
	return invoicer, mailer
}
