package api

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"

	"fr.latosa-escrima/core"
	"github.com/resend/resend-go/v2"
)

type ContactForm struct {
	Firstname string `json:"firstname"`
	Lastname  string `json:"lastname"`
	EMail     string `json:"email"`
	Subject   string `json:"subject"`
	Message   string `json:"message"`
}

func HandleContact(w http.ResponseWriter, r *http.Request) {
	// TODO: Warning email not being sent ?
	var form ContactForm
	err := json.NewDecoder(r.Body).Decode(&form)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusBadRequest)
		return
	}

	apiKey := os.Getenv("RESEND_APIKEY")
	sendTo := os.Getenv("SMTP_EMAIL")
	client := resend.NewClient(apiKey)
	params := &resend.SendEmailRequest{
		From:    "onboarding@resend.dev",
		To:      []string{sendTo},
		Subject: form.Subject,
		Html: fmt.Sprintf("<h1><strong>%s %s</strong> (%s) vous a envoyé un mail.</h1></br></br>%s",
			form.Firstname, form.Lastname, form.EMail, form.Message),
		ReplyTo: form.EMail,
	}

	sent, err := client.Emails.Send(params)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusBadRequest)
		return
	}

	fmt.Println(*sent)

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Email sent.",
	}.Respond(w, http.StatusAccepted)
}
