package controllers

import (
	"api/database"
	"api/dbaccess"
	"api/models"
	"strconv"
	"time"

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

func AddEvent(c *fiber.Ctx) error {
	var data map[string]string
	var audience int
	var startdt time.Time

	if err := c.BodyParser(&data); err != nil {
		return err
	}

	u, err := strconv.Atoi(data["user"])
	if err != nil {
		c.Status(fiber.StatusBadRequest)
		return c.JSON(fiber.Map{
			"message": "Invalid value for Event Owner",
		})
	}

	user := dbaccess.GetUserById(u)

	if user.Id == 0 {
		c.Status(fiber.StatusBadRequest)
		return c.JSON(fiber.Map{
			"message": "Event Owner not found",
		})
	}

	if data["audience"] == "" {
		c.Status(fiber.StatusBadRequest)
		return c.JSON(fiber.Map{
			"message": "Audience not defined",
		})
	} else {
		audience, err = strconv.Atoi(data["audience"])
		if err != nil {
			c.Status(fiber.StatusBadRequest)
			return c.JSON(fiber.Map{
				"message": "Invalid value for audience",
			})
		}
	}

	dateformat := "02/01/2006 15:04"
	if data["startDt"] == "" {
		c.Status(fiber.StatusBadRequest)
		return c.JSON(fiber.Map{
			"message": "Start date not defined",
		})
	} else {
		startdt, err = time.Parse(dateformat, data["startDt"])
		if err != nil {
			c.Status(fiber.StatusBadRequest)
			return c.JSON(fiber.Map{
				"message": "Invalid value for start date",
			})
		}
	}

	event := models.Event{
		Name:             data["name"],
		UserId:           user.Id,
		User:             user,
		ExpectedAudience: audience,
		ExpectedDate:     startdt,
		EventType:        data["eventtype"],
	}

	database.DB.Create(&event)

	if event.Id == 0 {
		c.Status(fiber.StatusBadRequest)
		return c.JSON(fiber.Map{
			"message": "Cannot create event",
		})
	}

	c.SendStatus(fiber.StatusCreated)
	return c.JSON(event)
}
