package repository

import (
	"hyapp-admin-server/internal/model"
	"time"
)

func (s *Store) FindUserByUsername(username string) (*model.User, error) {
	var user model.User
	err := s.db.Preload("Roles.Permissions").Where("username = ?", username).First(&user).Error
	if err != nil {
		return nil, err
	}

	return &user, nil
}

func (s *Store) FindUserByID(id uint) (*model.User, error) {
	var user model.User
	err := s.db.Preload("Roles.Permissions").First(&user, id).Error
	if err != nil {
		return nil, err
	}

	return &user, nil
}

func PermissionsForUser(user model.User) []string {
	set := map[string]struct{}{}
	for _, role := range user.Roles {
		for _, permission := range role.Permissions {
			set[permission.Code] = struct{}{}
		}
	}

	out := make([]string, 0, len(set))
	for code := range set {
		out = append(out, code)
	}

	return out
}

func (s *Store) TouchUserLogin(id uint) error {
	nowMS := time.Now().UTC().UnixMilli()
	return s.db.Model(&model.User{}).Where("id = ?", id).Updates(map[string]any{
		"last_login_at_ms": &nowMS,
		"updated_at_ms":    nowMS,
	}).Error
}

func (s *Store) CreateRefreshToken(token model.RefreshToken) error {
	return s.db.Create(&token).Error
}

func (s *Store) FindRefreshToken(hash string) (*model.RefreshToken, error) {
	var token model.RefreshToken
	err := s.db.Where("token_hash = ? AND revoked_at_ms IS NULL AND expires_at_ms > ?", hash, time.Now().UTC().UnixMilli()).First(&token).Error
	if err != nil {
		return nil, err
	}

	return &token, nil
}

func (s *Store) RevokeRefreshToken(hash string) error {
	nowMS := time.Now().UTC().UnixMilli()
	return s.db.Model(&model.RefreshToken{}).Where("token_hash = ? AND revoked_at_ms IS NULL", hash).Update("revoked_at_ms", &nowMS).Error
}
