package repositories

import (
	"strconv"

	"gorm.io/gorm"

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

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

type GORMPrintJobRepository struct {
	DB *gorm.DB
}

func NewGORMPrintJobRepository(db *gorm.DB) PrintJobRepository {
	return &GORMPrintJobRepository{
		DB: db,
	}
}

func (t *GORMPrintJobRepository) Create(printJob models.PrintJob) (models.PrintJob, error) {
	result := t.DB.Create(&printJob)

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

	return printJob, nil
}

func (t *GORMPrintJobRepository) GetAll() ([]models.PrintJob, error) {
	var printJobs []models.PrintJob
	result := t.DB.Preload("ShopItem").Preload("Variant").Preload("PaperType").Preload("CoverPaperType").Find(&printJobs)

	return printJobs, result.Error
}

func (t *GORMPrintJobRepository) GetById(id string) (models.PrintJob, error) {
	printJobId, err := strconv.Atoi(id)

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

	var printJob models.PrintJob
	result := t.DB.Preload("ShopItem").Preload("Variant").Preload("PaperType").Preload("CoverPaperType").First(&printJob, uint(printJobId))

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

	return printJob, nil
}

func (t *GORMPrintJobRepository) Update(printJob models.PrintJob) (models.PrintJob, error) {
	result := t.DB.Save(&printJob)
	if result.Error != nil {
		return models.PrintJob{}, result.Error
	}

	return printJob, nil
}

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

	if err != nil {
		return err
	}

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