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

	query := db.Model(&models.AssetCustody{})
	if v := c.Query("asset_id"); v != "" {
		query = query.Where("asset_id = ?", v)
	}
	if v := c.Query("custodian_name"); v != "" {
		query = query.Where("custodian_name LIKE ?", "%"+v+"%")
	}

	var total int64
	query.Count(&total)

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

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

func CreateAssetCustody(c *gin.Context) {
	db := common.GetDB()
	var item models.AssetCustody
	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", "asset_custody", "create_asset_custody", &item.ID, item)
	OK(c, item)
}

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

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