//
// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.
//

package models

import (
	"time"

	"github.com/veypi/vigo"
)

// User 全局用户表
type User struct {
	vigo.Model
	Username      string     `json:"username" gorm:"uniqueIndex;size:50;not null"`
	Password      string     `json:"-" gorm:"size:255"` // bcrypt hash
	Nickname      string     `json:"nickname" gorm:"size:50"`
	Avatar        string     `json:"avatar" gorm:"size:500"`
	Email         *string    `json:"email" gorm:"uniqueIndex;size:100"`
	Phone         *string    `json:"phone" gorm:"uniqueIndex;size:20"`
	Status        int        `json:"status" gorm:"default:1"` // 0:禁用 1:正常 2:未激活
	EmailVerified bool       `json:"email_verified" gorm:"default:false"`
	PhoneVerified bool       `json:"phone_verified" gorm:"default:false"`
	LastLoginAt   *time.Time `json:"last_login_at"`
}

// Identity 第三方身份绑定
type Identity struct {
	vigo.Model
	UserID       string     `json:"user_id" gorm:"index;not null"`
	Provider     string     `json:"provider" gorm:"size:20;not null"`             // google/github/wechat/ldap
	ProviderUID  string     `json:"provider_uid" gorm:"index;size:100;not null"` // 第三方唯一ID
	ProviderName string     `json:"provider_name" gorm:"size:50"`
	Avatar       string     `json:"avatar" gorm:"size:500"`
	Email        string     `json:"email" gorm:"size:100"`
	AccessToken  string     `json:"-" gorm:"size:500"`
	RefreshToken string     `json:"-" gorm:"size:500"`
	ExpiresAt    *time.Time `json:"-"`

	// 外键关联
	User User `json:"user,omitempty" gorm:"foreignKey:UserID;references:ID"`
}

// Session 登录会话
type Session struct {
	vigo.Model
	UserID     string    `json:"user_id" gorm:"index;not null"`
	TokenID    string    `json:"token_id" gorm:"uniqueIndex;size:36"` // JWT jti
	Type       string    `json:"type" gorm:"size:20;not null"`        // access/refresh
	DeviceInfo string    `json:"device_info" gorm:"size:200"`
	IP         string    `json:"ip" gorm:"size:50"`
	ExpiresAt  time.Time `json:"expires_at"`
	Revoked    bool      `json:"revoked" gorm:"default:false"`
	RevokedAt  *time.Time `json:"revoked_at"`

	// 外键关联
	User User `json:"user,omitempty" gorm:"foreignKey:UserID;references:ID"`
}

// UserStatus 用户状态常量
const (
	UserStatusDisabled = 0
	UserStatusActive   = 1
	UserStatusInactive = 2
)

// IsActive 用户是否激活
func (u *User) IsActive() bool {
	return u.Status == UserStatusActive
}
