package common

import (
  "log"
  "reflect"
  "github.com/gofiber/fiber/v2"
   "github.com/go-playground/validator/v10"
)

type Failure struct {
	Message string `json:"message"`
}

func IfErrNil(err error, c *fiber.Ctx) error {
	if err != nil {
		log.Output(10, err.Error())
		c.SendStatus(fiber.StatusInternalServerError)
		return c.JSON(Failure{err.Error()})
	}

	return err
}

func ReceivePost[T any](c *fiber.Ctx) (*T, error) {
  var result *T
  result = new(T)

  if err := c.BodyParser(result); err != nil {
    log.Println(err);
    return result, err
  }

  var validate *validator.Validate
  validate = validator.New(validator.WithRequiredStructEnabled())

  if err := validate.Struct(result); err != nil {
    validationErrors := err.(validator.ValidationErrors)
    log.Println(validationErrors)
    return result, err
  }

  return result, nil
}

func ReflectOnPost(typeOf reflect.Type, c *fiber.Ctx) (reflect.Value, error) {
  var result_val reflect.Value

  result_val = reflect.New(typeOf)
  result := result_val.Interface()

  if err := c.BodyParser(result); err != nil {
    log.Println(err);
    return result_val, err
  }

  var validate *validator.Validate
  validate = validator.New(validator.WithRequiredStructEnabled())

  if err := validate.Struct(result); err != nil {
    validationErrors := err.(validator.ValidationErrors)
    log.Println(validationErrors)
    return result_val, err
  }

  return result_val, nil
}
