package controllers

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

	"net/http"
	// "strconv"
	"github.com/gin-gonic/gin"

	"GoMembership/pkg/logger"
)

type MembershipController struct {
	Service services.MembershipService
}

type MembershipData struct {
	APIKey string                   `json:"api_key"`
	Model  models.SubscriptionModel `json:"model"`
}

func (mc *MembershipController) RegisterSubscription(c *gin.Context) {
	var regData MembershipData
	if err := c.ShouldBindJSON(&regData); err != nil {
		logger.Error.Printf("Couln't decode subscription data: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Couldn't decode subscription data"})
	}

	// Register Subscription
	id, err := mc.Service.RegisterSubscription(&regData.Model)
	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,
	})
}
