package reports

import (
	db "ttime/internal/database"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/log"
	"github.com/golang-jwt/jwt/v5"
)

// GetAllWeeklyReports retrieves all weekly reports for a user in a specific project
func GetAllWeeklyReports(c *fiber.Ctx) error {
	// Extract the necessary parameters from the token
	user := c.Locals("user").(*jwt.Token)
	claims := user.Claims.(jwt.MapClaims)
	username := claims["name"].(string)

	// Extract project name and week from query parameters
	projectName := c.Params("projectName")
	target_user := c.Query("targetUser") // The user whose reports are being requested

	// If the target user is not empty, use it as the username
	if target_user == "" {
		target_user = username
	}

	log.Info(username, " trying to get all weekly reports for: ", target_user)

	if projectName == "" {
		log.Info("Missing project name")
		return c.Status(400).SendString("Missing project name")
	}

	// If the user is not a project manager, they can only view their own reports
	pm, err := db.GetDb(c).IsProjectManager(username, projectName)
	if err != nil {
		log.Info("Error checking if user is project manager:", err)
		return c.Status(500).SendString(err.Error())
	}

	if pm == false && target_user != username {
		log.Info("Unauthorized access")
		return c.Status(403).SendString("Unauthorized access")
	}

	// Retrieve weekly reports for the user in the project from the database
	reports, err := db.GetDb(c).GetAllWeeklyReports(target_user, projectName)
	if err != nil {
		log.Error("Error getting weekly reports for user:", target_user, "in project:", projectName, ":", err)
		return c.Status(500).SendString(err.Error())
	}

	log.Info("Returning weekly report")
	// Return the retrieved weekly report
	return c.JSON(reports)
}