package database

import (
	"testing"
	"time"

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

// --- sortMigrationNames ---

func TestSortMigrationNames_Alphabetical(t *testing.T) {
	input := []string{"charlie", "alpha", "bravo"}
	result := sortMigrationNames(input)

	assert.Equal(t, []string{"alpha", "bravo", "charlie"}, result)
	// Verify original slice is not mutated
	assert.Equal(t, []string{"charlie", "alpha", "bravo"}, input)
}

func TestSortMigrationNames_Empty(t *testing.T) {
	result := sortMigrationNames([]string{})
	assert.Equal(t, []string{}, result)
	assert.Len(t, result, 0)
}

// --- buildAppliedSet ---

func TestBuildAppliedSet_Multiple(t *testing.T) {
	applied := []DataMigration{
		{ID: 1, Name: "20250101_first", AppliedAt: time.Now()},
		{ID: 2, Name: "20250201_second", AppliedAt: time.Now()},
		{ID: 3, Name: "20250301_third", AppliedAt: time.Now()},
	}

	set := buildAppliedSet(applied)

	assert.Len(t, set, 3)
	assert.True(t, set["20250101_first"])
	assert.True(t, set["20250201_second"])
	assert.True(t, set["20250301_third"])
	assert.False(t, set["nonexistent"])
}

func TestBuildAppliedSet_Empty(t *testing.T) {
	set := buildAppliedSet([]DataMigration{})
	assert.Len(t, set, 0)
}

// --- filterPending ---

func TestFilterPending_SomePending(t *testing.T) {
	names := []string{"20250101_first", "20250201_second", "20250301_third"}
	applied := map[string]bool{
		"20250101_first": true,
	}

	pending := filterPending(names, applied)

	assert.Equal(t, []string{"20250201_second", "20250301_third"}, pending)
}

func TestFilterPending_AllApplied(t *testing.T) {
	names := []string{"20250101_first", "20250201_second"}
	applied := map[string]bool{
		"20250101_first":  true,
		"20250201_second": true,
	}

	pending := filterPending(names, applied)

	assert.Nil(t, pending)
}

func TestFilterPending_NoneApplied(t *testing.T) {
	names := []string{"20250101_first", "20250201_second", "20250301_third"}
	applied := map[string]bool{}

	pending := filterPending(names, applied)

	assert.Equal(t, []string{"20250101_first", "20250201_second", "20250301_third"}, pending)
}
