package config

import (
	"encoding/json"
	"os"
	"path/filepath"
)

// Config holds the CLI configuration
type Config struct {
	ServerURL string `json:"server_url"`
	Token     string `json:"token"`
	UserEmail string `json:"user_email"`
}

// configPath returns the path to the config file
func configPath() (string, error) {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(homeDir, ".arp_cli", "config.json"), nil
}

// Load reads the configuration from disk
func Load() (*Config, error) {
	path, err := configPath()
	if err != nil {
		return nil, err
	}

	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return &Config{}, nil
		}
		return nil, err
	}

	var cfg Config
	if err := json.Unmarshal(data, &cfg); err != nil {
		return nil, err
	}

	return &cfg, nil
}

// Save writes the configuration to disk
func Save(cfg *Config) error {
	path, err := configPath()
	if err != nil {
		return err
	}

	// Ensure directory exists
	dir := filepath.Dir(path)
	if err := os.MkdirAll(dir, 0700); err != nil {
		return err
	}

	data, err := json.MarshalIndent(cfg, "", "  ")
	if err != nil {
		return err
	}

	return os.WriteFile(path, data, 0600)
}

// Clear removes the stored token but keeps the server URL
func Clear() error {
	cfg, err := Load()
	if err != nil {
		return err
	}
	cfg.Token = ""
	cfg.UserEmail = ""
	return Save(cfg)
}

// SetServerURL updates the server URL in the config
func SetServerURL(url string) error {
	cfg, err := Load()
	if err != nil {
		return err
	}
	cfg.ServerURL = url
	return Save(cfg)
}

// SetToken updates the token and user email in the config
func SetToken(token, email string) error {
	cfg, err := Load()
	if err != nil {
		return err
	}
	cfg.Token = token
	cfg.UserEmail = email
	return Save(cfg)
}
