package recipes

import (
	"rmser/internal/domain/recipes"

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

type pgRepository struct {
	db *gorm.DB
}

func NewRepository(db *gorm.DB) recipes.Repository {
	return &pgRepository{db: db}
}

func (r *pgRepository) SaveRecipes(list []recipes.Recipe) error {
	return r.db.Transaction(func(tx *gorm.DB) error {
		for _, recipe := range list {
			if err := tx.Omit("Items").Clauses(clause.OnConflict{
				Columns:   []clause.Column{{Name: "id"}},
				UpdateAll: true,
			}).Create(&recipe).Error; err != nil {
				return err
			}
			if err := tx.Where("recipe_id = ?", recipe.ID).Delete(&recipes.RecipeItem{}).Error; err != nil {
				return err
			}
			if len(recipe.Items) > 0 {
				if err := tx.Create(&recipe.Items).Error; err != nil {
					return err
				}
			}
		}
		return nil
	})
}
