package config

import (
	"encoding/json"
	"os"

	"git.schreifuchs.ch/lou-taylor/accounting/internal/email"
	"github.com/caarlos0/env/v10"
)

// PDF holds the configuration for the PDF generator.
type PDF struct {
	Hostname string `json:"hostname" env:"HOSTNAME"`
}

// Gitea holds the configuration for the Gitea client.
type Gitea struct {
	URL   string `json:"url" env:"URL"`
	Token string `json:"token" env:"TOKEN"`
}

// Config holds the configuration for the entire application.
type Config struct {
	Email email.Config `json:"email" envPrefix:"EMAIL_"`
	PDF   PDF          `json:"pdf" envPrefix:"PDF_"`
	Gitea Gitea        `json:"gitea" envPrefix:"GITEA_"`
}

// Load loads the configuration from a JSON file and environment variables.
func Load(path string) (*Config, error) {
	cfg := &Config{}

	file, err := os.Open(path)
	if err == nil {
		defer file.Close()
		decoder := json.NewDecoder(file)
		if err := decoder.Decode(cfg); err != nil {
			return nil, err
		}
	} else if !os.IsNotExist(err) {
		return nil, err
	}

	if err := env.Parse(cfg); err != nil {
		return nil, err
	}

	return cfg, nil
}
