package middleware

import (
	"fmt"
	"verification-platform-backend/internal/database"
	"verification-platform-backend/internal/model"
	"verification-platform-backend/pkg/crypto"

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

func AppCrypto() gin.HandlerFunc {
	return func(c *gin.Context) {
		appKey := c.Param("appKey")
		if appKey == "" {
			c.Next()
			return
		}

		var app model.Application
		if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
			c.Next()
			return
		}

		var encryptType crypto.EncryptType
		switch app.EncryptType {
		case "aes":
			encryptType = crypto.EncryptTypeAES
		case "rc4":
			encryptType = crypto.EncryptTypeRC4
		default:
			encryptType = crypto.EncryptTypeNone
		}

		cryptoManager := crypto.NewCryptoManager(encryptType, app.EncryptKey)
		shouldEncrypt := encryptType != crypto.EncryptTypeNone
		
		fmt.Printf("[AppCrypto] AppKey: %s, EncryptType: %s, EncryptKey: %s, ShouldEncrypt: %v\n", 
			appKey, app.EncryptType, app.EncryptKey, shouldEncrypt)
		
		c.Set("should_encrypt_response", shouldEncrypt)
		c.Set("crypto_manager", cryptoManager)

		c.Next()
	}
}
