package Database

import (
	"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"

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

func GetPosts(page, pageSize int) ([]Models.Post, error) {
	var (
		posts []Models.Post
		err   error
	)

	if page == 0 {
		page = 1
	}

	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	err = DB.Offset(page).
		Limit(pageSize).
		Find(&posts).
		Error

	return posts, err
}

func GetFrontPagePosts() ([]Models.Post, error) {
	var (
		posts []Models.Post
		err   error
	)

	err = DB.Where("front_page = ?", true).
		Order("order asc").
		Find(&posts).
		Error

	return posts, err
}

func GetPostById(id string) (Models.Post, error) {
	var (
		postData Models.Post
		err      error
	)

	err = DB.Preload(clause.Associations).
		First(&postData, "id = ?", id).
		Error

	return postData, err
}

func CreatePost(postData *Models.Post) error {
	return DB.Session(&gorm.Session{FullSaveAssociations: true}).
		Create(postData).
		Error
}

func UpdatePost(id string, postData *Models.Post) (Models.Post, error) {
	var (
		err error
	)

	DB.Model(postData).
		Where("id = ?", id).
		Association("PostLinks").
		Replace(postData.PostLinks)

	err = DB.Model(&Models.Post{}).
		Select("*").
		Omit("id", "created_at", "updated_at", "deleted_at").
		Where("id = ?", id).
		Updates(postData).
		Error

	if err != nil {
		return Models.Post{}, err
	}

	return GetPostById(id)
}

func DeletePost(postData *Models.Post) error {
	return DB.Session(&gorm.Session{FullSaveAssociations: true}).
		Delete(postData).
		Error
}
