package dao

import (
	"time"

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

// 帖子草稿表
type Draft struct {
	UserId    int32          `gorm:"primaryKey;comment:'发帖人ID'"`
	CreatedAt time.Time      `gorm:"type:datetime(0)"`
	UpdatedAt time.Time      `gorm:"type:datetime(0)"`
	Title     string         `gorm:"index;type:varchar(255);comment:'帖子标题'"`
	Content   string         `gorm:"type:text;comment:'帖子内容'"`
	RoleIds   datatypes.JSON `gorm:"comment:'关联角色'"`
}

// 如果存在，就更新。如果不存在，就创建
func Draft_Save(data *Draft) error {
	return s.db.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "user_id"}}, DoUpdates: clause.AssignmentColumns([]string{"title", "content", "role_ids"})}).Create(&data).Error
}

func Draft_Query(userId int32) (*Draft, error) {
	var data Draft
	if err := s.db.Where("user_id = ?", userId).First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &data, nil
}

func Draft_Delete(userId int32) error {
	data := Draft{UserId: userId}
	return s.db.Delete(&data).Error
}
