package service

import (
	"testing"

	"github.com/orchard9/rdev/internal/sdlc"
)

func TestSDLCCallbackService_MapArtifactType(t *testing.T) {
	tests := []struct {
		genType    string
		wantType   sdlc.ArtifactType
		wantErr    bool
		wantErrMsg string
	}{
		{
			genType:  "spec",
			wantType: sdlc.ArtifactSpec,
		},
		{
			genType:  "design",
			wantType: sdlc.ArtifactDesign,
		},
		{
			genType:  "tasks",
			wantType: sdlc.ArtifactTasks,
		},
		{
			genType:    "code",
			wantErr:    true,
			wantErrMsg: "code artifact type does not have a corresponding SDLC artifact",
		},
		{
			genType:  "qa",
			wantType: sdlc.ArtifactQAResults,
		},
		{
			genType:    "unknown",
			wantErr:    true,
			wantErrMsg: "unknown artifact type",
		},
		{
			genType:    "",
			wantErr:    true,
			wantErrMsg: "unknown artifact type",
		},
	}

	svc := &SDLCCallbackService{}

	for _, tt := range tests {
		t.Run(tt.genType, func(t *testing.T) {
			got, err := svc.mapArtifactType(tt.genType)

			if tt.wantErr {
				if err == nil {
					t.Errorf("mapArtifactType(%q) expected error, got nil", tt.genType)
				} else if tt.wantErrMsg != "" && !containsSubstr(err.Error(), tt.wantErrMsg) {
					t.Errorf("mapArtifactType(%q) error = %q, want containing %q",
						tt.genType, err.Error(), tt.wantErrMsg)
				}
				return
			}

			if err != nil {
				t.Fatalf("mapArtifactType(%q) unexpected error: %v", tt.genType, err)
			}

			if got != tt.wantType {
				t.Errorf("mapArtifactType(%q) = %v, want %v", tt.genType, got, tt.wantType)
			}
		})
	}
}

// containsSubstr checks if s contains substr.
func containsSubstr(s, substr string) bool {
	return len(s) >= len(substr) && (s == substr || len(substr) == 0 || indexOf(s, substr) >= 0)
}

// indexOf returns the index of substr in s, or -1 if not found.
func indexOf(s, substr string) int {
	for i := 0; i <= len(s)-len(substr); i++ {
		if s[i:i+len(substr)] == substr {
			return i
		}
	}
	return -1
}
