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

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

	var total int64
	query.Count(&total)

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

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

func CreateSeason(c *gin.Context) {
	db := common.GetDB()
	var item models.Season
	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", "season", "create_season", &item.ID, item)
	OK(c, item)
}

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

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