package dao

import (
	"time"

	"gorm.io/datatypes"
	"gorm.io/gorm"
)

// 帖子表
type Post struct {
	BaseModel
	UserId  int32          `gorm:"index;comment:'发帖人ID'"`
	Title   string         `gorm:"index;type:varchar(255);comment:'帖子标题'"`
	Content string         `gorm:"type:text;comment:'帖子内容'"`
	RoleIds datatypes.JSON `gorm:"comment:'关联角色'"`
}

func Post_Insert(data *Post) (uint64, error) {
	if err := s.db.Create(data).Error; err != nil {
		return 0, err
	}
	return uint64(data.ID), nil
}

func Post_Query(postId uint64) (*Post, error) {
	var data Post
	if err := s.db.Where("id = ?", postId).First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &data, nil
}

func Post_Page_Query(start_time, stop_time time.Time, role_id int32) ([]*Post, error) {
	var list []*Post
	var err error
	if role_id == int32(0) { // 不能根据role_id查询
		err = s.db.Where("created_at between ? and ?", start_time, stop_time).Find(&list).Error
	} else {
		err = s.db.Where("created_at between ? and ?", start_time, stop_time).Where(datatypes.JSONArrayQuery("role_ids").Contains(role_id)).Find(&list).Error
	}
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return list, nil
}

func Post_Delete(postId uint64) error {
	data := Post{}
	data.ID = postId
	return s.db.Delete(&data).Error
}
