package handlers

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func (h *Handler) GetAdminRegistration(c *gin.Context) {
	cfg := h.store.GetRegistrationConfig()
	c.JSON(http.StatusOK, gin.H{
		"requireInviteCode": cfg.RequireInviteCode,
		"invites":           cfg.Invites,
	})
}

func (h *Handler) PutAdminRegistrationPolicy(c *gin.Context) {
	var req updateRegistrationPolicyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
		return
	}
	if err := h.store.SetRegistrationRequireInvite(req.RequireInviteCode); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save registration policy"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"requireInviteCode": req.RequireInviteCode})
}

func (h *Handler) PostAdminInvite(c *gin.Context) {
	var req createInviteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
		return
	}
	entry, err := h.store.AddInviteEntry(req.Note, req.MaxUses, strings.TrimSpace(req.ExpiresAt))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusCreated, gin.H{"invite": entry})
}

func (h *Handler) DeleteAdminInvite(c *gin.Context) {
	code := strings.TrimSpace(c.Param("code"))
	if err := h.store.DeleteInviteEntry(code); err != nil {
		if strings.Contains(err.Error(), "not found") {
			c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"deleted": true})
}
