package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/titansys/appy-builder/internal/client"
	"github.com/titansys/appy-builder/internal/config"
)

// AuthMiddleware handles server_key authentication
type AuthMiddleware struct {
	config      *config.Config
	titanClient *client.TitanClient
}

// NewAuthMiddleware creates a new authentication middleware
func NewAuthMiddleware(cfg *config.Config, titanClient *client.TitanClient) *AuthMiddleware {
	return &AuthMiddleware{
		config:      cfg,
		titanClient: titanClient,
	}
}

// ValidateServerKey validates the server_key from URL parameter
func (m *AuthMiddleware) ValidateServerKey() gin.HandlerFunc {
	return func(c *gin.Context) {
		serverKey := c.Param("server_key")

		if serverKey == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status":  http.StatusUnauthorized,
				"message": "Server key is required",
				"data":    false,
			})
			c.Abort()
			return
		}

		if m.config.Hosted {
			// Validate as purchase code via TitanSystems API
			valid, err := m.titanClient.VerifyPurchaseCode(serverKey)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{
					"status":  http.StatusInternalServerError,
					"message": "License verification failed",
					"data":    false,
				})
				c.Abort()
				return
			}
			if !valid {
				c.JSON(http.StatusForbidden, gin.H{
					"status":  http.StatusForbidden,
					"message": "Invalid purchase code",
					"data":    false,
				})
				c.Abort()
				return
			}
			// Store purchase code in context for later use by handlers
			c.Set("purchase_code", serverKey)
		} else {
			// Match against config key
			if serverKey != m.config.Key {
				c.JSON(http.StatusUnauthorized, gin.H{
					"status":  http.StatusUnauthorized,
					"message": "Invalid server key",
					"data":    false,
				})
				c.Abort()
				return
			}
		}

		c.Next()
	}
}
