package service

import (
	"context"
	"fmt"

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

type RedisHashable interface {
	RedisHashable() (map[string]any, error)
	model.BeaconEvent | model.HTTPLocation
}

func persistBeaconValkey[T RedisHashable](id string, msg T, client *redis.Client, ctx context.Context) error {
	key := fmt.Sprintf("beacon:%s", id)
	hashM, err := msg.RedisHashable()
	if err != nil {
		fmt.Println("Error in converting location into hashmap for Redis insert: ", err)
		return err
	}
	if err := client.HSet(ctx, key, hashM).Err(); err != nil {
		fmt.Println("Error in persisting set in Redis key: ", key)
		return err
	}
	if err := client.SAdd(ctx, "beacons", key).Err(); err != nil {
		fmt.Println("Error in adding beacon to the beacons list for get all operation: ", err)
		return err
	}
	return nil
}

func LocationToBeaconService(msg model.HTTPLocation, appState *appcontext.AppState, client *redis.Client, ctx context.Context) error {
	id := msg.ID
	beacon, ok := appState.GetBeacon(id)
	if !ok {
		appState.UpdateBeacon(id, model.Beacon{ID: id, Location: msg.Location, Distance: msg.Distance, LastSeen: msg.LastSeen, PreviousConfidentLocation: msg.PreviousConfidentLocation})
	} else {
		beacon.ID = id
		beacon.Location = msg.Location
		beacon.Distance = msg.Distance
		beacon.LastSeen = msg.LastSeen
		beacon.PreviousConfidentLocation = msg.PreviousConfidentLocation
		appState.UpdateBeacon(id, beacon)
	}
	if err := persistBeaconValkey(id, msg, client, ctx); err != nil {
		return err
	}

	return nil
}

func EventToBeaconService(msg model.BeaconEvent, appState *appcontext.AppState, client *redis.Client, ctx context.Context) error {
	id := msg.ID
	beacon, ok := appState.GetBeacon(id)
	if !ok {
		appState.UpdateBeacon(id, model.Beacon{ID: id, BeaconType: msg.Type, HSBattery: int64(msg.Battery), Event: msg.Event})
	} else {
		beacon.ID = id
		beacon.BeaconType = msg.Type
		beacon.HSBattery = int64(msg.Battery)
		beacon.Event = msg.Event
		appState.UpdateBeacon(id, beacon)
	}
	if err := persistBeaconValkey(id, msg, client, ctx); err != nil {
		return err
	}

	return nil
}
