package system

import (
	"context"
	"testing"

	adapter "github.com/casbin/gorm-adapter/v3"
	"github.com/glebarez/sqlite"
	"github.com/stretchr/testify/require"
	"gorm.io/gorm"
)

func TestInitCasbinIncludesApiRoleManagementPolicies(t *testing.T) {
	db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
	require.NoError(t, err)
	require.NoError(t, db.AutoMigrate(&adapter.CasbinRule{}))

	_, err = (&initCasbin{}).InitializeData(context.WithValue(context.Background(), "db", db))
	require.NoError(t, err)

	requiredPolicies := []adapter.CasbinRule{
		{Ptype: "p", V0: "888", V1: "/api/getApiRoles", V2: "GET"},
		{Ptype: "p", V0: "888", V1: "/api/setApiRoles", V2: "POST"},
	}
	for _, policy := range requiredPolicies {
		var count int64
		require.NoError(t, db.Model(&adapter.CasbinRule{}).Where(policy).Count(&count).Error)
		require.Equalf(t, int64(1), count, "missing policy: %+v", policy)
	}
}
