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 ListPointsRules(c *gin.Context) {
	db := common.GetDB()
	p := ParsePagination(c)

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

	var total int64
	query.Count(&total)

	var items []models.PointsRule
	if err := query.Order("priority DESC, id ASC").Offset(p.Offset()).Limit(p.PageSize).Find(&items).Error; err != nil {
		Fail(c, http.StatusInternalServerError, "Failed to fetch points rules")
		return
	}
	OKList(c, items, total)
}

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

func CreatePointsRule(c *gin.Context) {
	db := common.GetDB()
	var item models.PointsRule
	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", "points_rule", "create_points_rule", &item.ID, item)
	OK(c, item)
}

func UpdatePointsRule(c *gin.Context) {
	db := common.GetDB()
	var existing models.PointsRule
	if err := db.First(&existing, c.Param("id")).Error; err != nil {
		Fail(c, http.StatusNotFound, "Points rule not found")
		return
	}
	var item models.PointsRule
	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", "points_rule", "update_points_rule", &item.ID, item)
	OK(c, item)
}

func DeletePointsRule(c *gin.Context) {
	db := common.GetDB()
	var item models.PointsRule
	if err := db.First(&item, c.Param("id")).Error; err != nil {
		Fail(c, http.StatusNotFound, "Points rule not found")
		return
	}
	if err := db.Delete(&item).Error; err != nil {
		Fail(c, http.StatusInternalServerError, err.Error())
		return
	}
	LogOp(c, "delete", "points_rule", "delete_points_rule", &item.ID, nil)
	OK(c, gin.H{"message": "deleted"})
}
