package Database

import "time"

func GetPostById(id string) (Post, error) {
	var (
		post Post
		e    error
	)

	e = DB.Model(&Post{}).
		Where("id = ?", id).
		First(&post).
		Error

	return post, e
}

func GetPostsList(limit int, offset int) ([]Post, error) {
	var (
		posts []Post
		e     error
	)

	e = DB.Model(&Post{}).
		Order("updated_at desc").
		Limit(limit).
		Offset(offset).
		Find(&posts).
		Error

	return posts, e
}

func GetPostsListBySubject(limit int, offset int, subject string) ([]Post, error) {
	var (
		posts []Post
		e     error
	)

	e = DB.Model(&Post{}).
		Where("subject = ?", subject).
		Order("updated_at desc").
		Limit(limit).
		Offset(offset).
		Find(&posts).
		Error

	return posts, e
}

func GetPostCountBySubject(subject string) (int64, error) {
	var (
		count int64
		e     error
	)

	e = DB.Model(&Post{}).
		Where("subject = ?", subject).
		Count(&count).
		Error

	return count, e
}

func CreatePost(post Post) error {
	return DB.Model(&Post{}).
		Create(&post).
		Error
}

func UpdatePost(post Post) error {
	return DB.Save(&post).Error
}

func GetLastUpdatedAt() (time.Time, error) {
	var (
		post Post
		e    error
	)

	e = DB.Model(&Post{}).
		Select("updated_at").
		Order("updated_at desc").
		Limit(1).
		Offset(0).
		First(&post).
		Error

	return post.UpdatedAt, e
}
