package shared

import (
	"strings"
	"time"

	"hyapp-admin-server/internal/model"
)

func UserDTOs(users []model.User) []map[string]any {
	out := make([]map[string]any, 0, len(users))
	for _, user := range users {
		out = append(out, UserDTO(user))
	}
	return out
}

func UserDTO(user model.User) map[string]any {
	roleNames := make([]string, 0, len(user.Roles))
	roleIDs := make([]uint, 0, len(user.Roles))
	for _, role := range user.Roles {
		roleNames = append(roleNames, role.Name)
		roleIDs = append(roleIDs, role.ID)
	}
	role := ""
	if len(roleNames) > 0 {
		role = strings.Join(roleNames, "、")
	}

	lastLogin := "-"
	if user.LastLoginAtMS != nil {
		lastLogin = time.UnixMilli(*user.LastLoginAtMS).UTC().Format("01-02 15:04")
	}
	teamName := UserTeamName(user)

	return map[string]any{
		"id":           user.ID,
		"account":      user.Username,
		"username":     user.Username,
		"name":         user.Name,
		"team":         teamName,
		"teamId":       user.TeamID,
		"teamName":     teamName,
		"status":       user.Status,
		"appScopeMode": user.AppScopeMode,
		"mfa":          BoolText(user.MFAEnabled),
		"mfaEnabled":   user.MFAEnabled,
		"lastLogin":    lastLogin,
		"lastLoginMs":  user.LastLoginAtMS,
		"roles":        user.Roles,
		"role":         role,
		"roleIds":      roleIDs,
		"permissions":  PermissionsForUser(user),
	}
}

func UserTeamName(user model.User) string {
	if strings.TrimSpace(user.TeamRecord.Name) != "" {
		return user.TeamRecord.Name
	}
	return strings.TrimSpace(user.Team)
}

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
}
