package infra

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

func TestAuditAppLocation(t *testing.T) {
	t.Run("detecta app.md en directorio prohibido cpp/apps", func(t *testing.T) {
		root := t.TempDir()

		// Violacion: cpp/apps/foo tiene app.md
		fooDir := filepath.Join(root, "cpp", "apps", "foo")
		if err := os.MkdirAll(fooDir, 0o755); err != nil {
			t.Fatal(err)
		}
		if err := os.WriteFile(filepath.Join(fooDir, "app.md"), []byte("name: foo\n"), 0o644); err != nil {
			t.Fatal(err)
		}

		// Ignorado: cpp/apps/bar sin app.md
		barDir := filepath.Join(root, "cpp", "apps", "bar")
		if err := os.MkdirAll(barDir, 0o755); err != nil {
			t.Fatal(err)
		}

		// Ignorado: apps/baz tiene app.md pero es el lugar canonico
		bazDir := filepath.Join(root, "apps", "baz")
		if err := os.MkdirAll(bazDir, 0o755); err != nil {
			t.Fatal(err)
		}
		if err := os.WriteFile(filepath.Join(bazDir, "app.md"), []byte("name: baz\n"), 0o644); err != nil {
			t.Fatal(err)
		}

		violations, err := AuditAppLocation(root)
		if err != nil {
			t.Fatalf("AuditAppLocation returned error: %v", err)
		}

		if len(violations) != 1 {
			t.Fatalf("expected 1 violation, got %d: %+v", len(violations), violations)
		}

		v := violations[0]
		wantPath := filepath.Join("cpp", "apps", "foo")
		if v.Path != wantPath {
			t.Errorf("Path: got %q, want %q", v.Path, wantPath)
		}
		if v.Kind != "app" {
			t.Errorf("Kind: got %q, want %q", v.Kind, "app")
		}
		if v.Lang != "cpp" {
			t.Errorf("Lang: got %q, want %q", v.Lang, "cpp")
		}
	})

	t.Run("directorios prohibidos inexistentes no producen error", func(t *testing.T) {
		root := t.TempDir()
		violations, err := AuditAppLocation(root)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if len(violations) != 0 {
			t.Errorf("expected 0 violations, got %d", len(violations))
		}
	})

	t.Run("detecta analysis.md en directorio prohibido python/analysis", func(t *testing.T) {
		root := t.TempDir()
		anaDir := filepath.Join(root, "python", "analysis", "my_analysis")
		if err := os.MkdirAll(anaDir, 0o755); err != nil {
			t.Fatal(err)
		}
		if err := os.WriteFile(filepath.Join(anaDir, "analysis.md"), []byte("name: my_analysis\n"), 0o644); err != nil {
			t.Fatal(err)
		}

		violations, err := AuditAppLocation(root)
		if err != nil {
			t.Fatalf("AuditAppLocation returned error: %v", err)
		}
		if len(violations) != 1 {
			t.Fatalf("expected 1 violation, got %d: %+v", len(violations), violations)
		}
		v := violations[0]
		if v.Kind != "analysis" || v.Lang != "python" {
			t.Errorf("got Kind=%q Lang=%q, want Kind=analysis Lang=python", v.Kind, v.Lang)
		}
	})
}
