package handlers

import (
	"net/http"
	"github.com/rs/zerolog/log"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"regexp"
	"time"
	"context"

	"hyperia/config"
	"github.com/mailgun/mailgun-go/v4"
)

type joinRequest struct {
	Email     string `json:"email"`
}

var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`)

func isValidEmail(email string) bool {
	return emailRegex.MatchString(email)
}

func HandleJoin(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Only POST allowed", http.StatusMethodNotAllowed)
		return
	}

	var creds joinRequest
	if err := json.NewDecoder(r.Body).Decode(&creds); err != nil {
		http.Error(w, "Invalid JSON", http.StatusBadRequest)
		return
	}

	if !isValidEmail(creds.Email) {
		http.Error(w, "Invalid email address", http.StatusBadRequest)
		return
	}

	// exists, err := EmailExists(creds.Email)
	// if err != nil {
	// 	log.Printf("Error checking email: %v", err)
	// 	http.Error(w, "Internal server error", http.StatusInternalServerError)
	// 	return
	// }
	// if exists {
	// 	http.Error(w, "Email already exists.", http.StatusConflict)
	// 	return
	// }

	// err = CreateApplicant(creds.Email)
	// if err != nil {
	// 	log.Printf("Error creating applicant: %v", err)
	// 	http.Error(w, "Failed to create applicant", http.StatusInternalServerError)
	// 	return
	// }

	// token, err := generateVerificationToken(creds.Email)
	// if err != nil {
	// 	log.Printf("Error generating verification token: %v", err)
	// 	http.Error(w, "Error, please try again later.", http.StatusInternalServerError)
	// 	return
	// }

	// err = sendWelcomeEmail(creds.Email, token)
	// if err != nil {
	// 	log.Printf("Error sending welcome email: %v", err)
	// 	http.Error(w, "Failed to send email", http.StatusInternalServerError)
	// 	return
	// }

	w.WriteHeader(http.StatusOK)
    w.Write([]byte("OK"))
}

func generateVerificationToken(email string) (string, error) {
	// Create 32 random bytes → 64-char hex string
	b := make([]byte, 32)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	token := hex.EncodeToString(b)

	// err := CreateApplicantVerification(email, token)
	// if err != nil {
	// 	return "", err
	// }

	return token, nil
}

func mailgunEmail(to string, token string) error {
	// link format:  https://hyperia.so/verify?token=7a1a7cb986437cf8868b18cf43d73ce2e947d65aef30b42419bab957f5e51a09
	domain := "mg.hyperia.so"
	apiKey := "aeb90a0c75ef782eab6fc3d48fdf4435-812b35f5-fe818055"

	mg := mailgun.NewMailgun(domain, apiKey)

	sender := "welcome@" + domain
	subject := "Verify Your Email"
	verifyLink := config.BASE_URL + "/verify?token=" + token
	body := "Thanks for signing up! Please verify your email by clicking this link: " + verifyLink
	
	message := mg.NewMessage(sender, subject, body, to)

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	_, _, err := mg.Send(ctx, message)
	return err
}

func sendWelcomeEmail(to string, token string) error {
	if config.ENV == "development" {
		verifyLink := config.BASE_URL + "/verify?token=" + token
		log.Debug().Msgf("email Verify Link: %s", verifyLink)
		return nil
	}

	return nil

	// query := `
	// 	INSERT INTO emails ("to", "from", subject, body, createdon, createdby, status)
	// 	VALUES ($1, $2, $3, $4, $5, $6, $7)
	// `

	// sender := "noreply@mail.hyperia.so"
	// subject := "Verify Your Email"
	// verifyLink := config.BASE_URL + "/verify?token=" + token
	// body := "Thanks for signing up! Please verify your email by clicking this link: " + verifyLink

	// _, err := DB.Exec(
	// 	query,
	// 	to,
	// 	sender,
	// 	subject,
	// 	body,
	// 	time.Now(),     // createdon
	// 	"go-backend",   // createdby
	// 	"pending",      // status
	// )

	// return err
}