package controllers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/go-playground/validator/v10"

	"GoMembership/internal/services"
	"GoMembership/pkg/logger"
)

type ContactController struct {
	EmailService *services.EmailService
}
type contactData struct {
	Email    string `form:"REPLY_TO" validate:"required,email"`
	Name     string `form:"name"`
	Message  string `form:"message" validate:"required"`
	Honeypot string `form:"username" validate:"eq="`
}

func (cc *ContactController) RelayContactRequest(c *gin.Context) {
	var msgData contactData

	if err := c.ShouldBind(&msgData); err != nil {
		// A bot is talking to us
		c.JSON(http.StatusNotAcceptable, gin.H{"error": "Not Acceptable"})
		return
	}

	validate := validator.New()
	if err := validate.Struct(msgData); err != nil {
		logger.Error.Printf("Couldn't validate contact form data: %#v: %v", msgData, err)
		c.HTML(http.StatusNotAcceptable, "contactForm_reply.html", gin.H{"Error": "Form validation failed. Please check again."})
		// c.JSON(http.StatusNotAcceptable, gin.H{"error": "Couldn't validate contact form data"})
		return
	}

	if err := cc.EmailService.RelayContactFormMessage(msgData.Email, msgData.Name, msgData.Message); err != nil {
		logger.Error.Printf("Couldn't send contact message mail: %v", err)
		c.HTML(http.StatusInternalServerError, "contactForm_reply.html", gin.H{"Error": "Email submission failed. Please try again."})
		// c.JSON(http.StatusInternalServerError, gin.H{"error": "Couldn't send mail"})
		return
	}

	// c.JSON(http.StatusAccepted, "Your message has been sent")
	c.HTML(http.StatusAccepted, "contactForm_reply.html", gin.H{"Success": true})
}
