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

	query := db.Model(&models.ProductLink{})
	if v := c.Query("asset_id"); v != "" {
		query = query.Where("asset_id = ?", v)
	}
	if v := c.Query("link_text"); v != "" {
		query = query.Where("link_text 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.ProductLink
	if err := query.Order("asset_id ASC, display_order ASC, id ASC").Offset(p.Offset()).Limit(p.PageSize).Find(&items).Error; err != nil {
		Fail(c, http.StatusInternalServerError, "Failed to fetch product links")
		return
	}
	OKList(c, items, total)
}

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

func CreateProductLink(c *gin.Context) {
	db := common.GetDB()
	var item models.ProductLink
	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", "product_link", "create_product_link", &item.ID, item)
	OK(c, item)
}

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

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