package entities

import (
	"time"

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

type Table 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;not null;index" json:"outlet_id" validate:"required"`
	TableName      string     `gorm:"not null;size:100" json:"table_name" validate:"required"`
	StartTime      *time.Time `gorm:"" json:"start_time"`
	Status         string     `gorm:"default:'available';size:50" json:"status"`
	OrderID        *uuid.UUID `gorm:"type:uuid;index" json:"order_id"`
	PaymentAmount  float64    `gorm:"type:decimal(10,2);default:0.00" json:"payment_amount"`
	PositionX      float64    `gorm:"type:decimal(10,2);default:0.00" json:"position_x"`
	PositionY      float64    `gorm:"type:decimal(10,2);default:0.00" json:"position_y"`
	Capacity       int        `gorm:"default:4" json:"capacity"`
	IsActive       bool       `gorm:"default:true" json:"is_active"`
	Metadata       Metadata   `gorm:"type:jsonb;default:'{}'" json:"metadata"`
	CreatedAt      time.Time  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt      time.Time  `gorm:"autoUpdateTime" json:"updated_at"`

	Organization Organization `gorm:"foreignKey:OrganizationID" json:"organization,omitempty"`
	Outlet       Outlet       `gorm:"foreignKey:OutletID" json:"outlet,omitempty"`
	Order        *Order       `gorm:"foreignKey:OrderID" json:"order,omitempty"`
}

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

func (Table) GetTableName() string {
	return "tables"
}

func (t *Table) IsAvailable() bool {
	return t.Status == "available"
}

func (t *Table) IsOccupied() bool {
	return t.Status == "occupied"
}

func (t *Table) CanBeOccupied() bool {
	return t.Status == "available" || t.Status == "cleaning"
}
