package main

import (
	"log"
	"net/http"
	"os"

	"github.com/gofiber/fiber/v2"
)

var logErrorCode *log.Logger

func init() {
	logFile, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
	}
	logErrorCode = log.New(logFile, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
}

func ErrorCodeLogsHandler(c *fiber.Ctx) error {
	if !IsUserAdmin(c) {
		return c.SendString("That's for admin, how did you manage to come here ?")
	}

	// Read the log file
	data, err := os.ReadFile("app.log")
	if err != nil {
		return c.SendStatus(http.StatusInternalServerError)
	}

	// Send the log file contents as the response
	return c.SendString(string(data))
}

func IsUserAdmin(c *fiber.Ctx) bool {
	var user User
	err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token")}).QuerySingle(edgeCtx, `
	SELECT global currentUser { id } LIMIT 1
	`, &user)
	if err != nil {
		return false
	}

	return user.ID.String() == "8185c6f0-1d8d-11ef-a7d1-cfc50efb05ff"
}
