package reports

import (
	db "ttime/internal/database"
	"ttime/internal/types"

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

func UpdateWeeklyReport(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)

	// Parse the request body into an UpdateWeeklyReport struct
	var updateReport types.UpdateWeeklyReport
	if err := c.BodyParser(&updateReport); err != nil {
		log.Info("Error parsing weekly report")
		return c.Status(400).SendString(err.Error())
	}

	// Make sure all the fields of the report are valid
	if updateReport.Week < 1 || updateReport.Week > 52 {
		log.Info("Invalid week number")
		return c.Status(400).SendString("Invalid week number")
	}

	if updateReport.DevelopmentTime < 0 || updateReport.MeetingTime < 0 || updateReport.AdminTime < 0 || updateReport.OwnWorkTime < 0 || updateReport.StudyTime < 0 || updateReport.TestingTime < 0 {
		log.Info("Invalid time report")
		return c.Status(400).SendString("Invalid time report")
	}

	// Update the weekly report in the database
	if err := db.GetDb(c).UpdateWeeklyReport(updateReport.ProjectName, username, updateReport.Week, updateReport.DevelopmentTime, updateReport.MeetingTime, updateReport.AdminTime, updateReport.OwnWorkTime, updateReport.StudyTime, updateReport.TestingTime); err != nil {
		log.Info("Error updating weekly report in db:", err)
		return c.Status(500).SendString(err.Error())
	}

	log.Info("Weekly report updated")
	return c.Status(200).SendString("Weekly report updated")
}