package fiko_mongo_store

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// MongoDB depolama yapısını tanımlıyoruz
type MongoStorage struct {
	collection *mongo.Collection
}

// Yeni MongoStorage oluşturuyoruz
func NewMongoStorage(client *mongo.Client, dbName, collName string) *MongoStorage {
	collection := client.Database(dbName).Collection(collName)
	return &MongoStorage{collection}
}

// Get methodu ile session verisini MongoDB'den okuyoruz
func (ms *MongoStorage) Get(key string) ([]byte, error) {
	var result map[string]interface{}
	err := ms.collection.FindOne(context.Background(), map[string]interface{}{"_id": key}).Decode(&result)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, nil // Session yoksa null döndür
		}
		return nil, err
	}
	return []byte(result["data"].(string)), nil
}

// Set methodu ile MongoDB'ye session verisini kaydediyoruz
func (ms *MongoStorage) Set(key string, value []byte) error {
	_, err := ms.collection.UpdateOne(
		context.Background(),
		map[string]interface{}{"_id": key},
		map[string]interface{}{"$set": map[string]interface{}{"data": string(value), "expires": time.Now().Add(24 * time.Hour)}},
		options.Update().SetUpsert(true), // Veri yoksa oluştur
	)
	return err
}

// Delete methodu ile MongoDB'den session verisini siliyoruz
func (ms *MongoStorage) Delete(key string) error {
	_, err := ms.collection.DeleteOne(context.Background(), map[string]interface{}{"_id": key})
	return err
}

// Session expiration kontrolü yapılacaksa, TTL Index'lerini kullanabilirsiniz.
func (ms *MongoStorage) CreateTTLIndex() {
	_, err := ms.collection.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys:    []string{"expires"},
		Options: options.Index().SetExpireAfterSeconds(0), // TTL index
	})
	if err != nil {
		log.Fatal("Error creating TTL index:", err)
	}
}
