package controllers

import (
	"GoMembership/internal/constants"
	"GoMembership/internal/models"
	"GoMembership/internal/services"
	"GoMembership/internal/utils"
	"strings"

	"net/http"

	"github.com/gin-gonic/gin"

	"GoMembership/pkg/errors"
	"GoMembership/pkg/logger"
)

type MembershipController struct {
	Service        services.MembershipService
	UserController interface {
		ExtractUserFromContext(*gin.Context) (*models.User, error)
	}
}

type MembershipData struct {
	// APIKey string                   `json:"api_key"`
	Subscription models.SubscriptionModel `json:"subscription"`
}

func (mc *MembershipController) RegisterSubscription(c *gin.Context) {
	var regData MembershipData

	requestUser, err := mc.UserController.ExtractUserFromContext(c)
	if err != nil {
		utils.RespondWithError(c, err, "Error extracting user from context in subscription registrationHandler", http.StatusBadRequest, "general", "server.validation.invalid_user_data")
		return
	}

	if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) {
		utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to register subscription", http.StatusForbidden, "user.user", "server.error.unauthorized")
		return
	}

	if err := c.ShouldBindJSON(&regData); err != nil {
		utils.HandleValidationError(c, err)
		return
	}

	// Register Subscription
	logger.Info.Printf("Registering subscription %v", regData.Subscription.Name)
	id, err := mc.Service.RegisterSubscription(&regData.Subscription)
	if err != nil {
		logger.Error.Printf("Couldn't register Membershipmodel: %v", err)
		if strings.Contains(err.Error(), "UNIQUE constraint failed") {
			c.JSON(http.StatusConflict, "Duplicate subscription name")
			return
		}
		c.JSON(http.StatusNotAcceptable, "Couldn't register Membershipmodel")
		return
	}
	logger.Info.Printf("registering subscription: %+v", regData)
	c.JSON(http.StatusCreated, gin.H{
		"status": "success",
		"id":     id,
	})
}

func (mc *MembershipController) UpdateHandler(c *gin.Context) {
	var regData MembershipData

	requestUser, err := mc.UserController.ExtractUserFromContext(c)
	if err != nil {
		utils.RespondWithError(c, err, "Error extracting user from context in subscription UpdateHandler", http.StatusBadRequest, "general", "server.validation.no_auth_tokenw")
		return
	}

	if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) {
		utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to update subscription", http.StatusForbidden, "user.user", "server.error.unauthorized")
		return
	}

	if err := c.ShouldBindJSON(&regData); err != nil {
		utils.HandleValidationError(c, err)
		return
	}

	// update Subscription
	logger.Info.Printf("Updating subscription %v", regData.Subscription.Name)
	id, err := mc.Service.UpdateSubscription(&regData.Subscription)
	if err != nil {
		logger.Error.Printf("Couldn't update Membershipmodel: %v", err)
		if strings.Contains(err.Error(), "UNIQUE constraint failed") {
			c.JSON(http.StatusConflict, "Duplicate subscription name")
			return
		}
		c.JSON(http.StatusNotAcceptable, "Couldn't update Membershipmodel")
		return
	}
	logger.Info.Printf("updating subscription: %+v", regData)
	c.JSON(http.StatusAccepted, gin.H{
		"status": "success",
		"id":     id,
	})
}

func (mc *MembershipController) DeleteSubscription(c *gin.Context) {
	type deleteData struct {
		Subscription struct {
			ID   uint   `json:"id"`
			Name string `json:"name"`
		} `json:"subscription"`
	}

	var data deleteData
	requestUser, err := mc.UserController.ExtractUserFromContext(c)
	if err != nil {
		utils.RespondWithError(c, err, "Error extracting user from context in subscription UpdateHandler", http.StatusBadRequest, "general", "server.validation.no_auth_tokenw")
		return
	}

	if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) {
		utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to update subscription", http.StatusForbidden, "user.user", "server.error.unauthorized")
		return
	}

	if err := c.ShouldBindJSON(&data); err != nil {
		utils.HandleValidationError(c, err)
		return
	}

	if err := mc.Service.DeleteSubscription(&data.Subscription.ID, &data.Subscription.Name); err != nil {
		utils.RespondWithError(c, err, "Error during subscription Deletion", http.StatusExpectationFailed, "subscription", "server.error.not_possible")
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Subscription deleted successfully"})
}

func (mc *MembershipController) GetSubscriptions(c *gin.Context) {
	subscriptions, err := mc.Service.GetSubscriptions(nil)
	if err != nil {
		logger.Error.Printf("Error retrieving subscriptions: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"errors": []gin.H{{
			"field": "general",
			"key":   "validation.internal_server_error",
		}}})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"subscriptions": subscriptions,
	})
}
