package models

import (
	"exhibitionCentre/database"
	"exhibitionCentre/logging"

	"gorm.io/gorm"
)

type VisitStatistic struct {
	gorm.Model
	Count        int  `gorm:"default:0"` // 访问次数，每日次数随访问量累加
	ExhibitionId uint `gorm:"not null"`  // 展览id
}

func init() {
	if err := database.DB.AutoMigrate(&VisitStatistic{}); err != nil {
		logging.Log.Fatalf("Mysql初始化VisitStatistic表失败: %s\n", err.Error())
	}
	logging.Log.Info("Mysql初始化VisitStatistic表完成.")
}

func CreateVisitStatistic(visit *VisitStatistic) error {
	if err := database.DB.Create(visit).Error; err != nil {
		return err
	}
	return nil // 成功创建
}

func GetTodayVisitStatistic(exhibitionId int) (*VisitStatistic, error) {
	var visit VisitStatistic
	if err := database.DB.Where("DATE(`created_at`) = CURDATE()").First(&visit, "exhibition_id = ?", exhibitionId).Error; err != nil {
		return nil, err
	}
	return &visit, nil
}

func DeleteVisitStatistics(exhibitionId int) error {
	if err := database.DB.Delete(&VisitStatistic{}, "exhibition_id = ?", exhibitionId).Error; err != nil {
		return err
	}
	return nil
}

func UpdateVisitStatistic(visit *VisitStatistic) error {
	if err := database.DB.Save(visit).Error; err != nil {
		return err
	}
	return nil
}

func GetVisitStatisticsByExhibitionId(exhibitionId int) ([]VisitStatistic, error) {
	var visits []VisitStatistic
	if err := database.DB.Order("created_at desc").Find(&visits, "exhibition_id = ?", exhibitionId).Error; err != nil {
		return visits, err
	}
	return visits, nil
}
