package main

import (
	"baron-sso-backend/internal/domain"
	"baron-sso-backend/internal/service"
	"context"
	"fmt"
	"log"
)

func main() {
	kratosAdmin := service.NewKratosAdminService()
	ctx := context.Background()

	identities, err := kratosAdmin.ListIdentities(ctx)
	if err != nil {
		log.Fatalf("Failed to list identities: %v", err)
	}

	count := 0
	for _, id := range identities {
		traits := id.Traits
		changed := false

		if r, ok := traits["role"].(string); ok {
			norm := domain.NormalizeRole(r)
			if norm != r && norm == domain.RoleUser {
				traits["role"] = norm
				changed = true
			}
		} else if g, ok := traits["grade"].(string); ok {
			if norm, ok := domain.NormalizeRoleAlias(g); ok {
				traits["role"] = norm
				delete(traits, "grade")
				changed = true
			}
		}

		if changed {
			_, err := kratosAdmin.UpdateIdentity(ctx, id.ID, traits, id.State)
			if err != nil {
				log.Printf("Failed to update %s: %v", id.ID, err)
			} else {
				count++
				fmt.Printf("Updated %s\n", id.ID)
			}
		}
	}
	fmt.Printf("Total updated: %d\n", count)
}
