package Database

import (
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"

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

// GetFriendRequestByID gets friend request
func GetFriendRequestByID(id string) (Models.FriendRequest, error) {
	var (
		friendRequest Models.FriendRequest
		err           error
	)

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

	return friendRequest, err
}

// GetFriendRequestsByUserID gets friend request by user id
func GetFriendRequestsByUserID(userID string, page int) ([]Models.FriendRequest, error) {
	var (
		friends []Models.FriendRequest
		offset  int
		err     error
	)

	offset = page * PageSize

	err = DB.Model(Models.FriendRequest{}).
		Where("user_id = ?", userID).
		Offset(offset).
		Limit(PageSize).
		Order("created_at DESC").
		Find(&friends).
		Error

	return friends, err
}

// CreateFriendRequest creates friend request
func CreateFriendRequest(friendRequest *Models.FriendRequest) error {
	return DB.Create(friendRequest).
		Error
}

// CreateFriendRequests creates multiple friend requests
func CreateFriendRequests(friendRequest *[]Models.FriendRequest) error {
	return DB.Create(friendRequest).
		Error
}

// UpdateFriendRequest Updates friend request
func UpdateFriendRequest(friendRequest *Models.FriendRequest) error {
	return DB.Where("id = ?", friendRequest.ID).
		Updates(friendRequest).
		Error
}

// DeleteFriendRequest deletes friend request
func DeleteFriendRequest(friendRequest *Models.FriendRequest) error {
	return DB.Session(&gorm.Session{FullSaveAssociations: true}).
		Delete(friendRequest).
		Error
}
