package config

import (
	"os"

	"gopkg.in/yaml.v3"
)

type Access struct {
	User string `yaml:"user"`
	Mode string `yaml:"mode"` // "read-only" or "read-write"
}

type Calendar struct {
	ID     string   `yaml:"id"`
	Owner  string   `yaml:"owner"`
	Access []Access `yaml:"access,omitempty"`
}

type User struct {
	Name        string `yaml:"name"`
	Password    string `yaml:"password"`
	PasswordCmd string `yaml:"password_cmd"`
}

type DatabaseConfig struct {
	URL string `yaml:"url"`
}

type ServerConfig struct {
	BindAddress string `yaml:"bind_address"`
	PublicURL   string `yaml:"public_url"`
	Redaction   string `yaml:"redaction_text"`
}

type Config struct {
	Server    ServerConfig   `yaml:"server"`
	Database  DatabaseConfig `yaml:"database"`
	Users     []User         `yaml:"users"`
	Calendars []Calendar     `yaml:"calendars"`
}

func Load(path string) (*Config, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var cfg Config
	err = yaml.NewDecoder(f).Decode(&cfg)
	if err != nil {
		return nil, err
	}

	cfg.setDefaults()
	return &cfg, nil
}

func (c *Config) setDefaults() {
	if c.Server.BindAddress == "" {
		c.Server.BindAddress = ":8080"
	}
	if c.Server.Redaction == "" {
		c.Server.Redaction = "Busy"
	}
	if c.Database.URL == "" {
		c.Database.URL = "postgres://nxcaldav@localhost:5432/nxcaldav?sslmode=disable"
	}
}
