package handlers

import (
	"context"

	"github.com/SamuelTariku/FortuneBet-Backend/internal/domain"
	"github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func GetLogsHandler(appCtx context.Context) fiber.Handler {
	return func(c *fiber.Ctx) error {
		client, err := mongo.Connect(appCtx, options.Client().ApplyURI("mongodb://root:secret@mongo:27017/?authSource=admin"))
		if err != nil {
			return fiber.NewError(fiber.StatusInternalServerError, "MongoDB connection failed: "+err.Error())
		}

		collection := client.Database("logdb").Collection("applogs")
		filter := bson.M{}
		opts := options.Find().SetSort(bson.D{{Key: "timestamp", Value: -1}}).SetLimit(100)

		cursor, err := collection.Find(appCtx, filter, opts)
		if err != nil {
			return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch logs: "+err.Error())
		}
		defer cursor.Close(appCtx)

		var logs []domain.LogEntry
		if err := cursor.All(appCtx, &logs); err != nil {
			return fiber.NewError(fiber.StatusInternalServerError, "Cursor decoding error: "+err.Error())
		}

		
		return c.JSON(logs)
	}
}
