package models

import (
	"math/rand"
	"time"

	"github.com/oklog/ulid/v2"
	"github.com/timetracker/backend/internal/types"
	"gorm.io/gorm"
)

type EntityBase struct {
	ID        types.ULID     `gorm:"type:bytea;primaryKey"`
	CreatedAt time.Time      `gorm:"index"`
	UpdatedAt time.Time      `gorm:"index"`
	DeletedAt gorm.DeletedAt `gorm:"index"`
}

// BeforeCreate is called by GORM before creating a record
func (eb *EntityBase) BeforeCreate(tx *gorm.DB) error {
	if eb.ID.Compare(types.ULID{}) == 0 { // If ID is empty
		// Generate a new types.ULID
		entropy := ulid.Monotonic(rand.New(rand.NewSource(time.Now().UnixNano())), 0)
		newID := ulid.MustNew(ulid.Timestamp(time.Now()), entropy)
		eb.ID = types.ULID{ULID: newID}
	}
	return nil
}
