package domain

import (
	"time"

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

// UserGroup represents a collection of users within a tenant.
type UserGroup struct {
	ID          string         `gorm:"primaryKey;type:uuid;default:gen_random_uuid()" json:"id"`
	TenantID    string         `gorm:"type:uuid;index;not null" json:"tenantId"`
	ParentID    *string        `gorm:"type:uuid;index" json:"parentId,omitempty"` // 상위 조직 ID
	Name        string         `gorm:"not null" json:"name"`
	Slug        string         `gorm:"index" json:"slug"` // 추가
	Description string         `json:"description"`
	UnitType    string         `json:"unitType"` // 부, 국, 팀, 셀 등
	CreatedAt   time.Time      `json:"createdAt"`
	UpdatedAt   time.Time      `json:"updatedAt"`
	DeletedAt   gorm.DeletedAt `gorm:"index" json:"-"`

	// Relationships
	Parent  *UserGroup `gorm:"foreignKey:ParentID" json:"parent,omitempty"`
	Members []User     `gorm:"-" json:"members,omitempty"`
}

type GroupCreateRequest struct {
	Name        string  `json:"name"`
	ParentID    *string `json:"parentId"`
	Description string  `json:"description"`
	UnitType    string  `json:"unitType"`
}

type GroupRole struct {
	TenantID   string `json:"tenantId"`
	TenantName string `json:"tenantName"`
	Relation   string `json:"relation"`
}

func (ug *UserGroup) TableName() string {
	return "user_groups"
}

func (ug *UserGroup) BeforeCreate(tx *gorm.DB) (err error) {
	if ug.ID == "" {
		ug.ID = uuid.NewString()
	}
	return
}
