package entities

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type Inventory struct {
	ID           uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	OutletID     uuid.UUID `gorm:"type:uuid;not null;index" json:"outlet_id" validate:"required"`
	ProductID    uuid.UUID `gorm:"type:uuid;not null;index" json:"product_id" validate:"required"`
	Quantity     int       `gorm:"not null;default:0" json:"quantity" validate:"min=0"`
	ReorderLevel int       `gorm:"default:0" json:"reorder_level" validate:"min=0"`
	UpdatedAt    time.Time `gorm:"autoUpdateTime" json:"updated_at"`

	Outlet  Outlet  `gorm:"foreignKey:OutletID" json:"outlet,omitempty"`
	Product Product `gorm:"foreignKey:ProductID" json:"product,omitempty"`
}

func (i *Inventory) BeforeCreate(tx *gorm.DB) error {
	if i.ID == uuid.Nil {
		i.ID = uuid.New()
	}
	return nil
}

func (Inventory) TableName() string {
	return "inventory"
}

func (i *Inventory) IsLowStock() bool {
	return i.Quantity <= i.ReorderLevel
}

func (i *Inventory) UpdateQuantity(delta int) {
	i.Quantity += delta
	if i.Quantity < 0 {
		i.Quantity = 0
	}
}
