package repository

import (
	"baron-sso-backend/internal/domain"
	"context"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestKetoOutboxRepository_ListCurrentBySubject(t *testing.T) {
	repo := NewKetoOutboxRepository(testDB)
	ctx := context.Background()

	require.NoError(t, testDB.Exec("DELETE FROM keto_outbox").Error)

	entries := []domain.KetoOutbox{
		{
			Namespace: "RelyingParty",
			Object:    "client-1",
			Relation:  "admins",
			Subject:   "User:user-1",
			Action:    domain.KetoOutboxActionCreate,
			Status:    domain.KetoOutboxStatusProcessed,
		},
		{
			Namespace: "RelyingParty",
			Object:    "client-1",
			Relation:  "admins",
			Subject:   "User:user-1",
			Action:    domain.KetoOutboxActionDelete,
			Status:    domain.KetoOutboxStatusProcessed,
		},
		{
			Namespace: "RelyingParty",
			Object:    "client-2",
			Relation:  "config_editor",
			Subject:   "User:user-1",
			Action:    domain.KetoOutboxActionCreate,
			Status:    domain.KetoOutboxStatusProcessed,
		},
		{
			Namespace: "RelyingParty",
			Object:    "client-3",
			Relation:  "audit_viewer",
			Subject:   "User:user-1",
			Action:    domain.KetoOutboxActionCreate,
			Status:    domain.KetoOutboxStatusFailed,
		},
		{
			Namespace: "Tenant",
			Object:    "tenant-1",
			Relation:  "members",
			Subject:   "User:user-1",
			Action:    domain.KetoOutboxActionCreate,
			Status:    domain.KetoOutboxStatusProcessed,
		},
	}
	for i := range entries {
		require.NoError(t, repo.Create(ctx, &entries[i]))
	}

	current, err := repo.ListCurrentBySubject(ctx, "RelyingParty", "User:user-1")
	require.NoError(t, err)
	require.Len(t, current, 1)
	require.Equal(t, "client-2", current[0].Object)
	require.Equal(t, "config_editor", current[0].Relation)
}
