package handlers

import (
	"encoding/json"
	"net/http"
	"os"
	"path/filepath"

	"github.com/gin-gonic/gin"
)

type configPayload struct {
	Backend  map[string]any `json:"backend"`
	Frontend map[string]any `json:"frontend"`
	Timezone string         `json:"timezone"`
}

// @Summary Lire la configuration
// @Tags Config
// @Produce json
// @Success 200 {object} configPayload
// @Failure 500 {object} map[string]string
// @Router /config [get]
func (h *Handler) GetConfig(c *gin.Context) {
	config, err := readConfig()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"erreur": "impossible de lire la configuration"})
		return
	}
	c.JSON(http.StatusOK, config)
}

// @Summary Mettre a jour la configuration
// @Tags Config
// @Accept json
// @Produce json
// @Param body body configPayload true "Configuration"
// @Success 200 {object} configPayload
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /config [put]
func (h *Handler) UpdateConfig(c *gin.Context) {
	var payload configPayload
	if err := c.ShouldBindJSON(&payload); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"erreur": "donnees invalides"})
		return
	}
	if payload.Timezone == "" {
		payload.Timezone = "Europe/Paris"
	}

	if err := writeConfig(payload); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"erreur": "impossible de sauvegarder la configuration"})
		return
	}
	c.JSON(http.StatusOK, payload)
}

func configPath() string {
	value := os.Getenv("CONFIG_PATH")
	if value == "" {
		return "./data/config.json"
	}
	return value
}

func defaultConfig() configPayload {
	return configPayload{
		Backend:  map[string]any{},
		Frontend: map[string]any{},
		Timezone: "Europe/Paris",
	}
}

func readConfig() (configPayload, error) {
	path := configPath()
	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			cfg := defaultConfig()
			if err := writeConfig(cfg); err != nil {
				return configPayload{}, err
			}
			return cfg, nil
		}
		return configPayload{}, err
	}

	var cfg configPayload
	if err := json.Unmarshal(data, &cfg); err != nil {
		return configPayload{}, err
	}
	if cfg.Timezone == "" {
		cfg.Timezone = "Europe/Paris"
	}
	return cfg, nil
}

func writeConfig(cfg configPayload) error {
	path := configPath()
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		return err
	}
	data, err := json.MarshalIndent(cfg, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(path, data, 0o644)
}
