package entity

import (
	"time"
)

// User 用户领域实体
type User struct {
	ID                 string
	Username           string
	PasswordHash       string
	Email              string
	Role               string
	WorkspaceID        string
	IsActive           bool
	MustChangePassword bool
	RevokedAfter       time.Time // 全局 Token 撤销时间
	CreatedAt          time.Time
	UpdatedAt          time.Time
}

// NewUser 创建新用户
func NewUser(username, passwordHash, email string) *User {
	now := time.Now()
	return &User{
		Username:     username,
		PasswordHash: passwordHash,
		Email:        email,
		Role:         "user",
		WorkspaceID:  DefaultWorkspaceID,
		IsActive:     true,
		RevokedAfter: time.Unix(0, 0), // 初始值：1970-01-01
		CreatedAt:    now,
		UpdatedAt:    now,
	}
}

// UpdatePassword 更新密码（会触发全局登出）
func (u *User) UpdatePassword(newPasswordHash string) {
	u.PasswordHash = newPasswordHash
	u.RevokedAfter = time.Now() // 撤销所有旧 Token
	u.UpdatedAt = time.Now()
}

// RevokeAllTokens 撤销所有 Token（强制全局登出）
func (u *User) RevokeAllTokens() {
	u.RevokedAfter = time.Now()
	u.UpdatedAt = time.Now()
}

// Validate 验证用户数据
func (u *User) Validate() error {
	if u.Username == "" {
		return ErrInvalidUsername
	}
	if u.PasswordHash == "" {
		return ErrInvalidPassword
	}
	if u.Role == "" {
		u.Role = "user"
	}
	if u.WorkspaceID == "" && u.Role != "admin" {
		u.WorkspaceID = DefaultWorkspaceID
	}
	return nil
}
