package main

import (
	"encoding/json"
	"fmt"
	"os"
)

// Config holds the web-only proof-of-concept server settings plus invoice
// defaults. It is read at startup only; edits made on the Settings page are
// kept in memory and are reset with the rest of the POC data every 10 minutes.
type Config struct {
	// Where the web server listens. Caddy can reverse-proxy to this.
	ListenAddr string `json:"listen_addr"`

	// Invoice / company details (editable in Settings for the current in-memory run).
	CompanyName      string  `json:"company_name"`
	CompanyAddress   string  `json:"company_address"`
	CompanyPhone     string  `json:"company_phone"`
	CompanyEmail     string  `json:"company_email"`
	CompanyWeb       string  `json:"company_web"`
	TaxID            string  `json:"tax_id"`
	BankInfo         string  `json:"bank_info"`
	PaymentTermsDays int     `json:"payment_terms_days"`
	MVGPercent       float64 `json:"mvg_percent"`
}

func loadConfig(path string) (Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return Config{}, fmt.Errorf("cannot read config %s: %w", path, err)
	}

	var cfg Config
	if err := json.Unmarshal(data, &cfg); err != nil {
		return Config{}, fmt.Errorf("cannot parse config: %w", err)
	}

	if cfg.ListenAddr == "" {
		cfg.ListenAddr = "127.0.0.1:8081"
	}
	if cfg.PaymentTermsDays <= 0 {
		cfg.PaymentTermsDays = 8
	}
	if cfg.MVGPercent <= 0 {
		cfg.MVGPercent = 25
	}
	return cfg, nil
}
