package admin

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gothinkster/golang-gin-realworld-example-app/common"
	"github.com/gothinkster/golang-gin-realworld-example-app/models"
)

func ListVIPTiers(c *gin.Context) {
	db := common.GetDB()
	p := ParsePagination(c)

	query := db.Model(&models.VIPTier{})
	if v := c.Query("is_active"); v != "" {
		query = query.Where("is_active = ?", v == "true")
	}
	if v := c.Query("tier_name"); v != "" {
		query = query.Where("tier_name LIKE ?", "%"+v+"%")
	}

	var total int64
	query.Count(&total)

	var items []models.VIPTier
	if err := query.Order("tier_level ASC").Offset(p.Offset()).Limit(p.PageSize).Find(&items).Error; err != nil {
		Fail(c, http.StatusInternalServerError, "Failed to fetch VIP tiers")
		return
	}
	OKList(c, items, total)
}

func GetVIPTier(c *gin.Context) {
	db := common.GetDB()
	var item models.VIPTier
	if err := db.First(&item, c.Param("id")).Error; err != nil {
		Fail(c, http.StatusNotFound, "VIP tier not found")
		return
	}
	OK(c, item)
}

func CreateVIPTier(c *gin.Context) {
	db := common.GetDB()
	var item models.VIPTier
	if err := BindJSONFlexTime(c, &item); err != nil {
		Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	item.ID = 0
	now := time.Now()
	if item.CreatedAt.IsZero() {
		item.CreatedAt = now
	}
	item.UpdatedAt = now
	if err := db.Create(&item).Error; err != nil {
		Fail(c, http.StatusInternalServerError, err.Error())
		return
	}
	LogOp(c, "create", "vip_tier", "create_vip_tier", &item.ID, item)
	OK(c, item)
}

func UpdateVIPTier(c *gin.Context) {
	db := common.GetDB()
	var existing models.VIPTier
	if err := db.First(&existing, c.Param("id")).Error; err != nil {
		Fail(c, http.StatusNotFound, "VIP tier not found")
		return
	}
	var item models.VIPTier
	if err := BindJSONFlexTime(c, &item); err != nil {
		Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	item.ID = existing.ID
	if existing.CreatedAt.IsZero() {
		item.CreatedAt = time.Now()
	} else {
		item.CreatedAt = existing.CreatedAt
	}
	if err := db.Save(&item).Error; err != nil {
		Fail(c, http.StatusInternalServerError, err.Error())
		return
	}
	LogOp(c, "update", "vip_tier", "update_vip_tier", &item.ID, item)
	OK(c, item)
}

func DeleteVIPTier(c *gin.Context) {
	db := common.GetDB()
	var item models.VIPTier
	if err := db.First(&item, c.Param("id")).Error; err != nil {
		Fail(c, http.StatusNotFound, "VIP tier not found")
		return
	}
	if err := db.Delete(&item).Error; err != nil {
		Fail(c, http.StatusInternalServerError, err.Error())
		return
	}
	LogOp(c, "delete", "vip_tier", "delete_vip_tier", &item.ID, nil)
	OK(c, gin.H{"message": "deleted"})
}
