package controllers

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

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

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

	_, err := utils.ProcessToken(c)
	if err != nil {
		return fiber.ErrUnauthorized
	}

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

	u, err := strconv.Atoi(data["user"])
	if err != nil {
		return fiber.ErrBadRequest
	}

	if data["name"] == "" || data["description"] == "" {
		return fiber.ErrBadRequest
	}

	user := dbaccess.GetUserById(u)

	if user.Id == 0 {
		return fiber.ErrBadRequest
	}

	if user.Blocked == "Y" || user.Cancelled == "Y" {
		return fiber.ErrForbidden
	}

	dateformat := "02/01/2006 15:04"
	if data["startDt"] == "" {
		return fiber.ErrBadRequest
	} else {
		startdt, err = time.Parse(dateformat, data["startDt"])
		if err != nil {
			return fiber.ErrBadRequest
		}
	}

	event := models.Event{
		Name:         data["name"],
		Description:  data["description"],
		UserId:       user.Id,
		Channel:      user.Channel,
		ExpectedDate: startdt,
		EventType:    data["eventtype"],
	}

	database.DB.Create(&event)

	if event.Id == 0 {
		return fiber.ErrNotAcceptable
	}

	return c.JSON(event)
}

// GetAllEvents - Returns all events
func GetAllEvents(c *fiber.Ctx) error {

	var events []models.Event

	// _, err := utils.ProcessToken(c)
	// if err != nil {
	// 	return fiber.ErrUnauthorized
	// }

	database.DB.Find(&events)

	if len(events) == 0 {
		return fiber.ErrNotFound
	}

	return c.JSON(events)
}
