package config

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

const AdminSettingsOverrideFilename = "admin_settings_overrides.json"

type adminSettingsOverrideFile struct {
	Format    string            `json:"format"`
	SavedAt   string            `json:"saved_at"`
	Overrides map[string]string `json:"overrides"`
}

func ReadAdminSettingsOverrides(path string) (map[string]string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return map[string]string{}, nil
		}
		return nil, err
	}

	var payload adminSettingsOverrideFile
	if err := json.Unmarshal(data, &payload); err != nil {
		return nil, err
	}
	if payload.Overrides == nil {
		return map[string]string{}, nil
	}
	normalized := make(map[string]string, len(payload.Overrides))
	for key, value := range payload.Overrides {
		nextKey, nextValue, err := NormalizeOverrideInput(key, value)
		if err != nil {
			return nil, err
		}
		normalized[nextKey] = nextValue
	}
	return normalized, nil
}

func WriteAdminSettingsOverrides(path string, overrides map[string]string) error {
	if overrides == nil {
		overrides = map[string]string{}
	}

	keys := make([]string, 0, len(overrides))
	for key := range overrides {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	normalized := make(map[string]string, len(overrides))
	for _, key := range keys {
		normalized[key] = overrides[key]
	}

	payload := adminSettingsOverrideFile{
		Format:    "warpbox.admin.settings.overrides.v1",
		SavedAt:   time.Now().UTC().Format(time.RFC3339),
		Overrides: normalized,
	}
	data, err := json.MarshalIndent(payload, "", "  ")
	if err != nil {
		return err
	}

	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		return err
	}
	return os.WriteFile(path, data, 0644)
}
