package entities

import (
	"time"

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

type AccountType string

const (
	AccountTypeCash      AccountType = "cash"
	AccountTypeWallet    AccountType = "wallet"
	AccountTypeBank      AccountType = "bank"
	AccountTypeCredit    AccountType = "credit"
	AccountTypeDebit     AccountType = "debit"
	AccountTypeAsset     AccountType = "asset"
	AccountTypeLiability AccountType = "liability"
	AccountTypeEquity    AccountType = "equity"
	AccountTypeRevenue   AccountType = "revenue"
	AccountTypeExpense   AccountType = "expense"
)

type Account 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"`
	ChartOfAccountID uuid.UUID   `gorm:"type:uuid;not null;index" json:"chart_of_account_id" validate:"required"`
	Name             string      `gorm:"not null;size:255" json:"name" validate:"required,min=1,max=255"`
	Number           string      `gorm:"not null;size:50" json:"number" validate:"required,min=1,max=50"`
	AccountType      AccountType `gorm:"not null;size:20" json:"account_type" validate:"required,oneof=cash wallet bank credit debit asset liability equity revenue expense"`
	OpeningBalance   float64     `gorm:"type:decimal(15,2);default:0.00" json:"opening_balance"`
	CurrentBalance   float64     `gorm:"type:decimal(15,2);default:0.00" json:"current_balance"`
	Description      *string     `gorm:"type:text" json:"description"`
	IsActive         bool        `gorm:"default:true" json:"is_active"`
	IsSystem         bool        `gorm:"default:false" json:"is_system"`
	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"`
	ChartOfAccount ChartOfAccount `gorm:"foreignKey:ChartOfAccountID" json:"chart_of_account,omitempty"`
}

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

func (Account) TableName() string {
	return "accounts"
}
