package fiko_mongo

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"time"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/fiber/v3/middleware/session"
	"github.com/gofiber/storage/mongodb"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var Client *mongo.Client
var Session *session.Store
var MongoStore *mongodb.Storage
var SessionConfig session.Config

func Init(app *fiber.App) {
	// MongoDB bağlantı URL'si
	databaseURL := "mongodb://127.0.0.1:8001/"
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)

	// MongoDB bağlantısını kuruyoruz
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(databaseURL))
	if err != nil {
		log.Fatal(err)
	}

	// Bağlantıyı global Client değişkenine atıyoruz
	Client = client
	setSessionMotor(app)
	setRoutes(app)
	setMiddleWare(app)
}

// GetMongoDBClient fonksiyonu mevcut MongoDB bağlantısını döndürür
func GetMongoDBClient() *mongo.Client {
	return Client
}

func GetSession() *session.Store {
	return Session
}

func setSessionMotor(_ *fiber.App) { // Session middleware
	// MongoDB'yi storage olarak ayarlıyoruz
	MongoStore = mongodb.New(mongodb.Config{
		Host:       "127.0.0.1",
		Port:       8001,
		Database:   "fikoyt",
		Collection: "go_sessions",
		Reset:      false,
	})

	// Session middleware yapılandırması
	SessionConfig = session.Config{
		Storage: MongoStore, CookieSecure: true, CookieHTTPOnly: true, CookieSameSite: "lax", Expiration: 24 * time.Hour, KeyLookup: "cookie:sid",
	}
	Session = session.New(SessionConfig)
	Session.RegisterType(bson.M{})
}

func setRoutes(app *fiber.App) {
	app.Get("/fikomongo", func(c fiber.Ctx) error {
		ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
		// MongoDB koleksiyonundan veri almak
		collection := GetMongoDBClient().Database("fikoyt").Collection("hareketler")

		// Find sorgusuna limit ve skip parametrelerini ekleyerek verileri alıyoruz
		findOptions := options.Find()
		findOptions.SetLimit(2)
		findOptions.SetSkip(0)

		cursor, err := collection.Find(ctx, bson.D{}, findOptions)
		if err != nil {
			log.Fatal(err)
		}
		defer cursor.Close(ctx)

		// Verileri tutacak bir dilim
		var results []bson.M
		cursor.All(ctx, &results)

		// Eğer cursor'dan çıkarken hata varsa
		if err := cursor.Err(); err != nil {
			log.Fatal(err)
		}

		SetSessionData(&session.Session{}, "test", results)
		// Session verisini JSON olarak döndürüyoruz
		return c.Status(200).JSON(finalData)
	})
}

func setMiddleWare(app *fiber.App) {
	app.Use(func(c fiber.Ctx) error {
		ses, _ := GetSession().Get(c)
		c.Locals("session", ses)
		return c.Next()
	})
}

// Dinamik veriyi session'a kaydeden yardımcı fonksiyon
func SetSessionData(s *session.Session, key string, value interface{}) error {
	// Veriyi JSON'a dönüştürmeye çalışıyoruz
	data, err := json.Marshal(value)
	if err != nil {
		return fmt.Errorf("failed to marshal value: %v", err)
	}

	// Veriyi session'a kaydediyoruz
	s.Set(key, data)

	// Session'ı kaydediyoruz
	if err := s.Save(); err != nil {
		return fmt.Errorf("failed to save session: %v", err)
	}

	return nil
}

// Session'dan veriyi almak için yardımcı fonksiyon
func GetSessionData(s *session.Session, key string) (interface{}, error) {
	// Session'dan veriyi alıyoruz
	value := s.Get(key)
	if value == nil {
		return nil, fmt.Errorf("no value found for key: %s", key)
	}

	// Veriyi JSON'dan çözümleyip interface{} olarak döndürüyoruz
	data, ok := value.([]byte) // Veriyi []byte olarak aldığınızı varsayıyoruz
	if !ok {
		return nil, fmt.Errorf("expected []byte, got %T", value)
	}

	var result interface{}
	if err := json.Unmarshal(data, &result); err != nil {
		return nil, fmt.Errorf("failed to unmarshal session data: %v", err)
	}

	return result, nil
}
