package quality

import (
	"context"
	"testing"
)

type panicDetector struct{}

func (p panicDetector) Name() string       { return "panic_detector" }
func (p panicDetector) Severity() Severity { return SeverityT2 }
func (p panicDetector) Detect(ctx context.Context, path string, config *Config) ([]Finding, error) {
	panic("boom")
}

type okDetector struct{}

func (o okDetector) Name() string       { return "ok_detector" }
func (o okDetector) Severity() Severity { return SeverityT1 }
func (o okDetector) Detect(ctx context.Context, path string, config *Config) ([]Finding, error) {
	return []Finding{{ID: "ok", Type: "ok", Title: "ok", File: "f.go", Line: 1, Severity: SeverityT1, Score: 1, Status: StatusOpen}}, nil
}

func TestScannerRecoversDetectorPanic(t *testing.T) {
	s := NewScanner(&Config{Path: ".", Language: "go"})
	s.RegisterDetector(panicDetector{})
	s.RegisterDetector(okDetector{})

	result, err := s.Scan(context.Background())
	if err != nil {
		t.Fatalf("scan should recover detector panic, got err: %v", err)
	}
	if len(result.Findings) != 2 {
		t.Fatalf("expected healthy finding plus detector_error, got %d", len(result.Findings))
	}

	hasOK := false
	hasDetectorError := false
	for _, f := range result.Findings {
		if f.ID == "ok" {
			hasOK = true
		}
		if f.Type == "detector_error" {
			hasDetectorError = true
		}
	}
	if !hasOK {
		t.Fatalf("expected to keep finding from healthy detector")
	}
	if !hasDetectorError {
		t.Fatalf("expected detector_error finding for panicing detector")
	}
}
