package migrations

import (
	"os"
	"path/filepath"
	"testing"
)

func TestPlanListsMigrationsWithChecksumsAndRollbackFiles(t *testing.T) {
	t.Parallel()

	dir := t.TempDir()
	writeFile(t, dir, "0002_second.up.sql", "SELECT 2;\n")
	writeFile(t, dir, "0002_second.down.sql", "SELECT -2;\n")
	writeFile(t, dir, "0001_first.up.sql", "SELECT 1;\n")

	plan, err := Plan(dir)
	if err != nil {
		t.Fatalf("Plan returned error: %v", err)
	}
	if len(plan) != 2 {
		t.Fatalf("Plan length = %d", len(plan))
	}
	if plan[0].Version != "0001_first" || plan[1].Version != "0002_second" {
		t.Fatalf("unexpected order: %+v", plan)
	}
	if plan[0].Checksum == "" || plan[1].Checksum == "" {
		t.Fatalf("expected checksums: %+v", plan)
	}
	if plan[0].RollbackAvailable {
		t.Fatalf("first migration should not have rollback: %+v", plan[0])
	}
	if !plan[1].RollbackAvailable || plan[1].DownFile == "" {
		t.Fatalf("second migration should have rollback: %+v", plan[1])
	}
}

func writeFile(t *testing.T, dir, name, body string) {
	t.Helper()
	if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o600); err != nil {
		t.Fatalf("write %s: %v", name, err)
	}
}
