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

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

	var total int64
	query.Count(&total)

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

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

	item.IsActive = !item.IsActive
	if item.CreatedAt.IsZero() {
		item.CreatedAt = time.Now()
	}
	if err := db.Save(&item).Error; err != nil {
		Fail(c, http.StatusInternalServerError, err.Error())
		return
	}

	LogOp(c, "update", "invite_code", "toggle_invite_code", &item.ID, gin.H{"is_active": item.IsActive})
	OK(c, item)
}

func UpdateInviteCode(c *gin.Context) {
	db := common.GetDB()
	var existing models.InviteCode
	if err := db.First(&existing, c.Param("id")).Error; err != nil {
		Fail(c, http.StatusNotFound, "Invite code not found")
		return
	}

	var body struct {
		ExpiresAt models.NullTime `json:"expires_at"`
	}
	if err := BindJSONFlexTime(c, &body); err != nil {
		Fail(c, http.StatusBadRequest, err.Error())
		return
	}

	existing.ExpiresAt = body.ExpiresAt
	if existing.CreatedAt.IsZero() {
		existing.CreatedAt = time.Now()
	}
	if err := db.Save(&existing).Error; err != nil {
		Fail(c, http.StatusInternalServerError, err.Error())
		return
	}
	LogOp(c, "update", "invite_code", "update_invite_code", &existing.ID, gin.H{"expires_at": body.ExpiresAt})
	OK(c, existing)
}
