package validator

import (
	"errors"
	"testing"
)

func TestPlaybook_WellFormedPasses(t *testing.T) {
	r, err := PlaybookValidator{}.Validate(Artifact{Playbook: map[string]any{
		"operation":      "fill: Welder x2 in Toledo, OH",
		"endorsed_names": []any{"W-123", "W-456"},
		"target_count":   2.0,
		"fingerprint":    "abc123",
	}})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if r.ElapsedMs < 0 {
		t.Errorf("elapsed_ms negative: %d", r.ElapsedMs)
	}
}

func TestPlaybook_EmptyEndorsedNamesFailsCompleteness(t *testing.T) {
	_, err := PlaybookValidator{}.Validate(Artifact{Playbook: map[string]any{
		"operation":      "fill: Welder x2 in Toledo, OH",
		"endorsed_names": []any{},
		"fingerprint":    "abc",
	}})
	var ve *ValidationError
	if !errors.As(err, &ve) || ve.Kind != ErrCompleteness {
		t.Fatalf("expected Completeness, got %v", err)
	}
}

func TestPlaybook_OverfullEndorsedNamesFailsCompleteness(t *testing.T) {
	_, err := PlaybookValidator{}.Validate(Artifact{Playbook: map[string]any{
		"operation":      "fill: Welder x1 in Toledo, OH",
		"endorsed_names": []any{"a", "b", "c"},
		"target_count":   1.0,
		"fingerprint":    "abc",
	}})
	var ve *ValidationError
	if !errors.As(err, &ve) || ve.Kind != ErrCompleteness {
		t.Fatalf("expected Completeness, got %v", err)
	}
}

func TestPlaybook_MissingFingerprintFailsSchema(t *testing.T) {
	_, err := PlaybookValidator{}.Validate(Artifact{Playbook: map[string]any{
		"operation":      "fill: X x1 in A, B",
		"endorsed_names": []any{"a"},
	}})
	var ve *ValidationError
	if !errors.As(err, &ve) || ve.Kind != ErrSchema || ve.Field != "fingerprint" {
		t.Fatalf("expected Schema/fingerprint, got %+v", err)
	}
}

func TestPlaybook_WrongOperationPrefixFailsSchema(t *testing.T) {
	_, err := PlaybookValidator{}.Validate(Artifact{Playbook: map[string]any{
		"operation":      "sms_draft: hello",
		"endorsed_names": []any{"a"},
		"fingerprint":    "x",
	}})
	var ve *ValidationError
	if !errors.As(err, &ve) || ve.Kind != ErrSchema {
		t.Fatalf("expected Schema, got %v", err)
	}
}

func TestPlaybook_WrongArtifactKindFailsSchema(t *testing.T) {
	_, err := PlaybookValidator{}.Validate(Artifact{FillProposal: map[string]any{}})
	var ve *ValidationError
	if !errors.As(err, &ve) || ve.Kind != ErrSchema || ve.Field != "artifact" {
		t.Fatalf("expected Schema/artifact, got %+v", err)
	}
}
