package internal

import (
	"errors"
	"golang.source-fellows.com/pattern/optimisticlocking/internal/model"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var db *gorm.DB

func InitSample() error {
	var err error

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,        // Don't include params in the SQL log
			Colorful:                  false,       // Disable color
		},
	)

	db, err = gorm.Open(
		mysql.Open("root:geheim@tcp(127.0.0.1:3306)/optimistic?charset=utf8mb4&parseTime=True&loc=Local"),
		&gorm.Config{
			Logger: newLogger,
		})
	if err != nil {
		log.Fatal("failed to connect database")
	}

	// Migrate the schema
	err = db.AutoMigrate(&model.Article{})
	if err != nil {
		return err
	}

	_ = db.Create(&model.Article{Model: gorm.Model{ID: 1}, Availability: 2})
	return nil
}

func OptimicticLockignSample() error {

	var firstArticle model.Article
	err := db.First(&firstArticle).Error
	if err != nil {
		return err
	}
	firstArticle.Availability = 3
	db.Updates(&firstArticle)

	var secondArticle model.Article
	err = db.First(&secondArticle).Error
	if err != nil {
		return err
	}

	log.Printf("found article with availability %d", firstArticle.Availability)
	log.Printf("found article with availability %d", secondArticle.Availability)
	firstArticle.Availability = 3
	secondArticle.Availability = 3

	update := db.Updates(&firstArticle)
	if update.Error != nil {
		return update.Error
	}
	if update.RowsAffected != 1 {
		return errors.New("no update with version")
	}

	update = db.Updates(&secondArticle)
	if update.Error != nil {
		return update.Error
	}
	if update.RowsAffected != 1 {
		return errors.New("no update with version")
	}

	return nil
}
