package controller

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/AFASystems/presence/internal/pkg/common/appcontext"
	"github.com/AFASystems/presence/internal/pkg/model"
	"github.com/redis/go-redis/v9"
	"github.com/segmentio/kafka-go"
)

func SettingsEditController(writer *kafka.Writer, appstate *appcontext.AppState, client *redis.Client, ctx context.Context) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		decoder := json.NewDecoder(r.Body)
		var inSettings model.SettingsVal
		if err := decoder.Decode(&inSettings); err != nil {
			http.Error(w, err.Error(), 400)
			fmt.Println("Error in decoding Settings body: ", err)
			return
		}

		if !settingsCheck(inSettings) {
			http.Error(w, "values must be greater than 0", 400)
			fmt.Println("settings values must be greater than 0")
			return
		}

		valueStr, err := json.Marshal(&inSettings)
		if err != nil {
			http.Error(w, "Error in encoding settings", 500)
			fmt.Println("Error in encoding settings: ", err)
			return
		}

		msg := kafka.Message{
			Value: valueStr,
		}

		if err := writer.WriteMessages(ctx, msg); err != nil {
			fmt.Println("error in sending Kafka message")
			http.Error(w, "Error in sending kafka message", 500)
			return
		}

		// if all is OK persist settings
		appstate.UpdateSettings(inSettings)
		appstate.PersistSettings(client, ctx)

		w.Write([]byte("ok"))
	}
}

func settingsCheck(settings model.SettingsVal) bool {
	if settings.LocationConfidence <= 0 || settings.LastSeenThreshold <= 0 || settings.HASendInterval <= 0 {
		return false
	}

	return true
}

func SettingsListController(appstate *appcontext.AppState, client *redis.Client, ctx context.Context) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		v, err := client.Get(ctx, "settings").Result()
		if err == redis.Nil {
			msg := "No list found for key settings, starting empty"
			fmt.Println(msg)
			http.Error(w, "msg", 500)
		} else if err != nil {
			msg := fmt.Sprintf("Error in connecting to Redis: %v, key: settings returning empty map\n", err)
			fmt.Println(msg)
			http.Error(w, msg, 500)
		} else {
			w.Write([]byte(v))
		}
	}
}
