package entities

import (
	"time"

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

type ChartOfAccount 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"`
	ChartOfAccountTypeID uuid.UUID  `gorm:"type:uuid;not null;index" json:"chart_of_account_type_id" validate:"required"`
	ParentID             *uuid.UUID `gorm:"type:uuid;index" json:"parent_id"`
	Name                 string     `gorm:"not null;size:255" json:"name" validate:"required,min=1,max=255"`
	Code                 string     `gorm:"not null;size:20" json:"code" validate:"required,min=1,max=20"`
	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"`
	ChartOfAccountType ChartOfAccountType `gorm:"foreignKey:ChartOfAccountTypeID" json:"chart_of_account_type,omitempty"`
	Parent             *ChartOfAccount    `gorm:"foreignKey:ParentID" json:"parent,omitempty"`
	Children           []ChartOfAccount   `gorm:"foreignKey:ParentID" json:"children,omitempty"`
	Accounts           []Account          `gorm:"foreignKey:ChartOfAccountID" json:"accounts,omitempty"`
}

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

func (ChartOfAccount) TableName() string {
	return "chart_of_accounts"
}
