package permissions

import (
	"context"
	"fmt"

	"github.com/oklog/ulid/v2"
	"github.com/timetracker/backend/internal/db"
	"gorm.io/gorm"
)

// LoadRoleWithPolicies loads a role with its associated policies from the database.
func LoadRoleWithPolicies(ctx context.Context, roleID ulid.ULID) (*Role, error) {
	var role Role
	err := db.GetEngine(ctx).Preload("Policies").First(&role, "id = ?", roleID).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("role with ID %s not found", roleID)
		}
		return nil, fmt.Errorf("failed to load role: %w", err)
	}
	return &role, nil
}
