package controller

import (
	"strconv"

	"github.com/QuantumNous/new-api/common"
	"github.com/QuantumNous/new-api/model"

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

func GetAllEmailQuotaRules(c *gin.Context) {
	list, err := model.GetAllEmailQuotaRules()
	if err != nil {
		common.ApiError(c, err)
		return
	}
	common.ApiSuccess(c, list)
}

type CreateEmailQuotaRuleRequest struct {
	EmailSuffix string `json:"email_suffix" binding:"required"`
	Quota       int64  `json:"quota" binding:"required"`
	Enabled     *bool  `json:"enabled"`
	Description string `json:"description"`
}

func CreateEmailQuotaRule(c *gin.Context) {
	var req CreateEmailQuotaRuleRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.ApiError(c, err)
		return
	}

	existing, _ := model.GetEmailQuotaRuleBySuffix(req.EmailSuffix)
	if existing != nil {
		common.ApiErrorMsg(c, "该邮箱后缀已存在")
		return
	}

	enabled := true
	if req.Enabled != nil {
		enabled = *req.Enabled
	}

	rule := &model.EmailQuotaRule{
		EmailSuffix: req.EmailSuffix,
		Quota:       req.Quota,
		Enabled:     enabled,
		Description: req.Description,
	}
	if err := rule.Insert(); err != nil {
		common.ApiError(c, err)
		return
	}

	common.ApiSuccess(c, rule)
}

type UpdateEmailQuotaRuleRequest struct {
	EmailSuffix string  `json:"email_suffix"`
	Quota       *int64  `json:"quota"`
	Enabled     *bool   `json:"enabled"`
	Description *string `json:"description"`
}

func UpdateEmailQuotaRule(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		common.ApiError(c, err)
		return
	}

	var req UpdateEmailQuotaRuleRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.ApiError(c, err)
		return
	}

	rule, err := model.GetEmailQuotaRuleById(id)
	if err != nil {
		common.ApiError(c, err)
		return
	}

	if req.EmailSuffix != "" && req.EmailSuffix != rule.EmailSuffix {
		existing, _ := model.GetEmailQuotaRuleBySuffix(req.EmailSuffix)
		if existing != nil && existing.Id != id {
			common.ApiErrorMsg(c, "该邮箱后缀已存在")
			return
		}
		rule.EmailSuffix = req.EmailSuffix
	}
	if req.Quota != nil {
		rule.Quota = *req.Quota
	}
	if req.Enabled != nil {
		rule.Enabled = *req.Enabled
	}
	if req.Description != nil {
		rule.Description = *req.Description
	}

	if err := rule.Update(); err != nil {
		common.ApiError(c, err)
		return
	}

	common.ApiSuccess(c, rule)
}

func DeleteEmailQuotaRule(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		common.ApiError(c, err)
		return
	}

	rule := &model.EmailQuotaRule{Id: id}
	if err := rule.Delete(); err != nil {
		common.ApiError(c, err)
		return
	}

	common.ApiSuccess(c, nil)
}
