package model

import (
	"github.com/QuantumNous/new-api/common"
	"gorm.io/gorm"
)

// PricingTag 定价标签表
// 用于对渠道定价进行分类和标识
type PricingTag struct {
	Id          int            `json:"id" gorm:"primaryKey"`
	Name        string         `json:"name" gorm:"size:64;not null;uniqueIndex"`
	Color       string         `json:"color" gorm:"size:16;default:'#1890ff'"`
	Description string         `json:"description" gorm:"type:text"`
	SortOrder   int            `json:"sort_order" gorm:"default:0"`
	CreatedTime int64          `json:"created_time" gorm:"bigint"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`
}

func (pt *PricingTag) Insert() error {
	pt.CreatedTime = common.GetTimestamp()
	return DB.Create(pt).Error
}

func (pt *PricingTag) Update() error {
	return DB.Model(&PricingTag{}).Where("id = ?", pt.Id).Updates(map[string]interface{}{
		"name":        pt.Name,
		"color":       pt.Color,
		"description": pt.Description,
		"sort_order":  pt.SortOrder,
	}).Error
}

func (pt *PricingTag) Delete() error {
	return DB.Delete(pt).Error
}

func GetPricingTagById(id int) (*PricingTag, error) {
	var pt PricingTag
	err := DB.First(&pt, id).Error
	if err != nil {
		return nil, err
	}
	return &pt, nil
}

func GetAllPricingTags() ([]*PricingTag, error) {
	var list []*PricingTag
	err := DB.Order("sort_order ASC, id ASC").Find(&list).Error
	return list, err
}

func GetPricingTagByName(name string) (*PricingTag, error) {
	var pt PricingTag
	err := DB.Where("name = ?", name).First(&pt).Error
	if err != nil {
		return nil, err
	}
	return &pt, nil
}
