package repositories

import (
	"strconv"

	"gorm.io/gorm"

	"git.dynamicdiscord.de/kalipso/zineshop/models"
)

type PaperRepository interface {
	Create(models.Paper) (models.Paper, error)
	GetAll() ([]models.Paper, error)
	GetById(string) (models.Paper, error)
	//GetByShopItemId(string) (models.Paper, error)
	Update(models.Paper) (models.Paper, error)
	DeleteById(string) error
}

type GORMPaperRepository struct {
	DB *gorm.DB
}

func NewGORMPaperRepository(db *gorm.DB) PaperRepository {
	return &GORMPaperRepository{
		DB: db,
	}
}

func (t *GORMPaperRepository) Create(tag models.Paper) (models.Paper, error) {
	result := t.DB.Create(&tag)

	if result.Error != nil {
		return models.Paper{}, result.Error
	}

	return tag, nil
}

func (t *GORMPaperRepository) GetAll() ([]models.Paper, error) {
	var tags []models.Paper
	result := t.DB.Find(&tags)

	return tags, result.Error
}

func (t *GORMPaperRepository) GetById(id string) (models.Paper, error) {
	tagId, err := strconv.Atoi(id)

	if err != nil {
		return models.Paper{}, err
	}

	var tag models.Paper
	result := t.DB.First(&tag, uint(tagId))

	if result.Error != nil {
		return models.Paper{}, result.Error
	}

	return tag, nil
}

func (t *GORMPaperRepository) Update(tag models.Paper) (models.Paper, error) {
	result := t.DB.Save(&tag)
	if result.Error != nil {
		return models.Paper{}, result.Error
	}

	return tag, nil
}

func (t *GORMPaperRepository) DeleteById(id string) error {
	tagId, err := strconv.Atoi(id)

	if err != nil {
		return err
	}

	result := t.DB.Delete(&models.Paper{}, tagId)
	return result.Error
}
