package repository

import (
	"context"
	"testing"

	"github.com/stretchr/testify/require"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"

	"security-center-backend/internal/model"
)

func TestPermissionRepositoryUpsertUpdatesExistingRowsWithoutZeroTimestamps(t *testing.T) {
	db, err := gorm.Open(sqlite.Open("file:permission-upsert?mode=memory&cache=shared"), &gorm.Config{})
	require.NoError(t, err)
	require.NoError(t, db.AutoMigrate(&model.Permission{}))

	repo := NewPermissionRepository(db)
	require.NoError(t, db.Exec(
		"INSERT INTO permissions (name, description, metadata, created_at, updated_at, deleted_at) VALUES (?, ?, ?, NULL, NULL, NULL)",
		"auth:manage_users",
		"old description",
		`{"menus":[]}`,
	).Error)

	err = repo.Upsert(context.Background(), []model.Permission{
		{
			Name:        "auth:manage_users",
			Description: "Manage user accounts and roles",
			Metadata:    model.JSONB{"menus": []string{"/dashboard/systems/users"}},
		},
		{
			Name:        "scan:view_batches",
			Description: "View scan batches and port exposure results",
			Metadata:    model.JSONB{"menus": []string{"/dashboard/scans/port-exposure"}},
		},
	})
	require.NoError(t, err)

	perms, err := repo.List(context.Background())
	require.NoError(t, err)
	require.Len(t, perms, 2)

	byName := make(map[string]model.Permission, len(perms))
	for _, perm := range perms {
		byName[perm.Name] = perm
	}
	require.Equal(t, "Manage user accounts and roles", byName["auth:manage_users"].Description)
	require.Equal(t, "View scan batches and port exposure results", byName["scan:view_batches"].Description)
}
