package routes

import (
	"context"
	"encoding/json"
	"net/http"

	"bssapp-backend/auth"
	"bssapp-backend/internal/mailer"
)

func TestMailHandler(ml *mailer.GraphMailer) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		claims, ok := auth.GetClaimsFromContext(r.Context())
		if !ok || claims == nil {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}

		var req struct {
			To string `json:"to"`
		}

		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, "invalid body", http.StatusBadRequest)
			return
		}

		err := ml.Send(
			context.Background(),
			mailer.Message{
				To:       []string{req.To},
				Subject:  "BSSApp Test Mail",
				BodyHTML: "<h3>🎉 Test mail başarılı</h3><p>Microsoft Graph üzerinden gönderildi.</p>",
			},
		)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		_ = json.NewEncoder(w).Encode(map[string]string{
			"message": "Mail gönderildi",
		})
	})
}
