package entities

import (
	"time"

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

type OrderIngredientTransaction struct {
	ID               uuid.UUID  `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	OrganizationID   uuid.UUID  `gorm:"type:uuid;not null;index" json:"organization_id" validate:"required"`
	OutletID         *uuid.UUID `gorm:"type:uuid;index" json:"outlet_id"`
	OrderID          uuid.UUID  `gorm:"type:uuid;not null;index" json:"order_id" validate:"required"`
	OrderItemID      *uuid.UUID `gorm:"type:uuid;index" json:"order_item_id"`
	ProductID        uuid.UUID  `gorm:"type:uuid;not null;index" json:"product_id" validate:"required"`
	ProductVariantID *uuid.UUID `gorm:"type:uuid;index" json:"product_variant_id"`
	IngredientID     uuid.UUID  `gorm:"type:uuid;not null;index" json:"ingredient_id" validate:"required"`
	GrossQty         float64    `gorm:"type:decimal(12,3);not null" json:"gross_qty" validate:"required,gt=0"`
	NetQty           float64    `gorm:"type:decimal(12,3);not null" json:"net_qty" validate:"required,gt=0"`
	WasteQty         float64    `gorm:"type:decimal(12,3);not null" json:"waste_qty" validate:"min=0"`
	Unit             string     `gorm:"size:50;not null" json:"unit" validate:"required,max=50"`
	TransactionDate  time.Time  `gorm:"not null;index" json:"transaction_date"`
	CreatedBy        uuid.UUID  `gorm:"type:uuid;not null;index" json:"created_by" validate:"required"`
	CreatedAt        time.Time  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt        time.Time  `gorm:"autoUpdateTime" json:"updated_at"`

	// Relations
	Organization   Organization   `gorm:"foreignKey:OrganizationID" json:"organization,omitempty"`
	Outlet         *Outlet        `gorm:"foreignKey:OutletID" json:"outlet,omitempty"`
	Order          Order          `gorm:"foreignKey:OrderID" json:"order,omitempty"`
	OrderItem      *OrderItem     `gorm:"foreignKey:OrderItemID" json:"order_item,omitempty"`
	Product        Product        `gorm:"foreignKey:ProductID" json:"product,omitempty"`
	ProductVariant *ProductVariant `gorm:"foreignKey:ProductVariantID" json:"product_variant,omitempty"`
	Ingredient     Ingredient     `gorm:"foreignKey:IngredientID" json:"ingredient,omitempty"`
	CreatedByUser  User           `gorm:"foreignKey:CreatedBy" json:"created_by_user,omitempty"`
}

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

func (OrderIngredientTransaction) TableName() string {
	return "order_ingredients_transactions"
}
