package service

import "testing"

func TestSafetyCheck_Safe(t *testing.T) {
	svc := NewSafetyService()

	tests := []struct {
		name  string
		title string
		url   string
	}{
		{"mkv file", "Movie.2024.1080p.BluRay.mkv", ""},
		{"mp4 file", "Show.S01E01.720p.WEB.mp4", "http://example.com/Show.S01E01.720p.WEB.mp4"},
		{"no extension", "Some-Release-Group", ""},
		{"nzb file", "Movie.2024.1080p.nzb", "http://indexer.example.com/api?t=get&id=123"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := svc.Check(tt.title, tt.url)
			if result != nil {
				t.Errorf("expected nil (safe), got blocked: %s", result.Reason)
			}
		})
	}
}

func TestSafetyCheck_DangerousTitle(t *testing.T) {
	svc := NewSafetyService()

	tests := []struct {
		name      string
		title     string
		wantExt   string
	}{
		{"exe in title", "Malware.2024.exe", ".exe"},
		{"bat in title", "Suspicious.Release.bat", ".bat"},
		{"scr in title", "Screensaver.scr", ".scr"},
		{"cmd in title", "Malware.Release.cmd", ".cmd"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := svc.Check(tt.title, "")
			if result == nil {
				t.Fatal("expected block, got nil")
			}
			if !result.Blocked {
				t.Error("expected Blocked=true")
			}
			if result.MatchedExtension != tt.wantExt {
				t.Errorf("expected extension %s, got %s", tt.wantExt, result.MatchedExtension)
			}
		})
	}
}

func TestSafetyCheck_DangerousURL(t *testing.T) {
	svc := NewSafetyService()

	result := svc.Check("normal-release", "http://example.com/file.bat")
	if result == nil {
		t.Fatal("expected block from URL extension, got nil")
	}
	if !result.Blocked {
		t.Error("expected Blocked=true")
	}
	if result.MatchedExtension != ".bat" {
		t.Errorf("expected .bat, got %s", result.MatchedExtension)
	}
}

func TestSafetyCheck_BothSafe(t *testing.T) {
	svc := NewSafetyService()

	result := svc.Check("Movie.2024.1080p.mkv", "http://example.com/Movie.2024.1080p.mkv")
	if result != nil {
		t.Errorf("expected nil (both safe), got blocked: %s", result.Reason)
	}
}

func TestSafetyCheck_ExtensionInMiddle(t *testing.T) {
	svc := NewSafetyService()

	// filepath.Ext returns the part after the LAST dot.
	// "Movie.EXE-group.1080p.mkv" has .mkv as extension — should NOT be blocked
	result := svc.Check("Movie.EXE-group.1080p.mkv", "")
	if result != nil {
		t.Errorf("expected nil (safe .mkv extension), got blocked: %s", result.Reason)
	}
}
