package models

import (
	"sync"
	"time"
)

type SkinHistoryItem struct {
	URL       string    `json:"url"`
	Name      string    `json:"name"`
	Timestamp time.Time `json:"timestamp"`
}

type User struct {
	Username    string            `json:"username"`
	Password    string            `json:"-"`
	Role        string            `json:"role"`
	Email       string            `json:"email"`
	CurrentSkin string            `json:"current_skin"`
	SkinHistory []SkinHistoryItem `json:"skin_history"`
}

var (
	users = make(map[string]*User)
	mu    sync.RWMutex
)

func CreateUser(username, password, email string) *User {
	mu.Lock()
	defer mu.Unlock()

	user := &User{
		Username:    username,
		Password:    password,
		Role:        "user",
		Email:       email,
		CurrentSkin: "/static/icons/Steve.png",
		SkinHistory: []SkinHistoryItem{},
	}
	users[username] = user
	return user
}

func GetUser(username string) (*User, bool) {
	mu.RLock()
	defer mu.RUnlock()
	user, exists := users[username]
	return user, exists
}

func ValidateUser(username, password string) bool {
	mu.RLock()
	defer mu.RUnlock()
	user, exists := users[username]
	if !exists {
		return false
	}
	return user.Password == password
}

func UpdateUser(username string, updates map[string]string) bool {
	mu.Lock()
	defer mu.Unlock()

	user, exists := users[username]
	if !exists {
		return false
	}

	if email, ok := updates["email"]; ok {
		user.Email = email
	}

	if skin, ok := updates["current_skin"]; ok {
		user.CurrentSkin = skin
	}

	if role, ok := updates["role"]; ok {
		user.Role = role
	}

	return true
}
