package models

import (
	"time"

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

// User model structure
type User struct {
	ID        uuid.UUID      `gorm:"type:uuid;default:gen_random_uuid();primaryKey" json:"id"`
	UserName  string         `json:"username"`
	Email     string         `gorm:"uniqueIndex;not null" json:"email"`
	Password  string         `json:"-"`                                         // Password shouldn't be returned in JSON
	Avatar    string         `gorm:"type:varchar(500)" json:"avatar,omitempty"` // Avatar URL from OAuth or uploaded
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`

	// Email verification: only required for email/password registration; OAuth users are treated as verified
	// Changed to *bool to handle false values correctly with GORM defaults
	EmailVerified    *bool      `gorm:"default:false" json:"email_verified"` // default false for email/password registration
	EmailVerifyToken string     `gorm:"index" json:"-"`
	EmailVerifiedAt  *time.Time `json:"email_verified_at,omitempty"`

	SocialAccounts []SocialAccount `gorm:"foreignKey:UserID" json:"social_accounts,omitempty"`
	Roles          []Role          `gorm:"many2many:user_roles;" json:"roles,omitempty"`
}

// Helper to safely get EmailVerified status
func (u *User) IsEmailVerified() bool {
	if u.EmailVerified == nil {
		return false
	}
	return *u.EmailVerified
}

// SocialAccount model structure
type SocialAccount struct {
	ID         uuid.UUID `gorm:"type:uuid;default:gen_random_uuid();primaryKey" json:"id"`
	UserID     uuid.UUID `gorm:"not null" json:"user_id"`
	Provider   string    `gorm:"not null" json:"provider"` // google, github
	ProviderID string    `gorm:"not null" json:"provider_id"`
	Email      string    `json:"email"`
	Name       string    `json:"name,omitempty"`       // Full name from provider
	AvatarURL  string    `json:"avatar_url,omitempty"` // Avatar URL from provider
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

// Hooks can be added here if needed
