package limpeza

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

func TestRemoverXmlOrfaos(t *testing.T) {
	dir := t.TempDir()
	validos := map[string]struct{}{
		"feedativo12345678": {},
	}

	mustWrite(t, filepath.Join(dir, "feedativo12345678.xml"), "<x/>")
	mustWrite(t, filepath.Join(dir, "orfaoxml123456789.xml"), "<x/>")
	mustWrite(t, filepath.Join(dir, "orfaoxml123456789.xml.tmp"), "<x/>")
	mustWrite(t, filepath.Join(dir, ".htaccess"), "Options -Indexes")

	n, err := RemoverXmlOrfaos(dir, validos)
	if err != nil {
		t.Fatal(err)
	}
	if n != 2 {
		t.Fatalf("esperado 2 removidos, got %d", n)
	}
	if _, err := os.Stat(filepath.Join(dir, "feedativo12345678.xml")); err != nil {
		t.Fatal("ativo deve permanecer")
	}
	if _, err := os.Stat(filepath.Join(dir, "orfaoxml123456789.xml")); !os.IsNotExist(err) {
		t.Fatal("órfão .xml deve sumir")
	}
	if _, err := os.Stat(filepath.Join(dir, ".htaccess")); err != nil {
		t.Fatal(".htaccess deve permanecer")
	}
}

func TestHashDeNomeArquivo_rejeitaCurto(t *testing.T) {
	if _, ok := hashDeNomeArquivo("abc.xml"); ok {
		t.Fatal("hash curto demais")
	}
}

func mustWrite(t *testing.T, path, body string) {
	t.Helper()
	if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
		t.Fatal(err)
	}
}
