package config

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

const (
	DefaultControlURL      = "https://sdp.mm.md"
	DefaultControllerInput = DefaultControlURL
)

type State struct {
	ControllerInput string `json:"controllerInput,omitempty"`
	AuthKey         string `json:"authKey,omitempty"`
}

func NormalizeControllerInput(input string) string {
	input = strings.TrimSpace(input)
	if input == "" {
		return DefaultControllerInput
	}
	return input
}

func ControlURLForControllerInput(input string) string {
	input = NormalizeControllerInput(input)
	if strings.HasPrefix(input, "http://") || strings.HasPrefix(input, "https://") {
		return input
	}

	controlURL := "https://sdp." + input
	if !strings.Contains(input, ".") {
		controlURL += ".com"
	}
	return controlURL
}

func DefaultPath(programData string) string {
	return filepath.Join(programData, "Mirage", "mirage-ui.json")
}

func Load(path string) (State, error) {
	data, err := os.ReadFile(path)
	switch {
	case err == nil:
	case errors.Is(err, os.ErrNotExist):
		return State{}, nil
	default:
		return State{}, err
	}

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

func Save(path string, state State) error {
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		return err
	}
	data, err := json.MarshalIndent(state, "", "  ")
	if err != nil {
		return err
	}
	data = append(data, '\n')
	return os.WriteFile(path, data, 0o600)
}
