package action

import (
	"context"
	"io"
	"log/slog"
	"testing"

	"github.com/andygrunwald/go-jira"
	"github.com/trivago/tgo/tcontainer"

	"github.com/tidbcloud/jiraport/pkg/entity"
)

func TestIsInternalAlert(t *testing.T) {
	tests := []struct {
		name string
		kind interface{}
		want bool
	}{
		{name: "internal", kind: "Internal", want: true},
		{name: "lowercase", kind: "internal", want: true},
		{name: "uppercase and whitespace", kind: "  INTERNAL\n", want: true},
		{name: "customer", kind: "Customer", want: false},
		{name: "empty", kind: "", want: false},
		{name: "non-string", kind: 1, want: false},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			unknowns := tcontainer.NewMarshalMap()
			unknowns["customfield_10159"] = tt.kind
			issue := &entity.RawIssue{Fields: &jira.IssueFields{Unknowns: unknowns}}

			if got := isInternalAlert(issue); got != tt.want {
				t.Fatalf("isInternalAlert() = %v, want %v", got, tt.want)
			}
		})
	}

	t.Run("missing issue", func(t *testing.T) {
		if isInternalAlert(nil) {
			t.Fatal("isInternalAlert(nil) = true, want false")
		}
	})

	t.Run("missing fields", func(t *testing.T) {
		if isInternalAlert(&entity.RawIssue{}) {
			t.Fatal("isInternalAlert() = true with missing fields, want false")
		}
	})
}

func TestAssignCommandExecSkipsInternalAlert(t *testing.T) {
	unknowns := tcontainer.NewMarshalMap()
	unknowns["customfield_10159"] = "Internal"
	fields := &jira.IssueFields{Unknowns: unknowns}
	execInfo := &entity.NotificationActionExecInfo{
		Notification: &entity.Notification{
			IssueKey: "O11Y-123",
			Issue: &entity.Issue{
				RawIssue: entity.RawIssue{Fields: fields},
			},
		},
	}
	cmd := &AssignCommand{
		logger:     slog.New(slog.NewTextHandler(io.Discard, nil)),
		needAssign: true,
	}

	tests := []struct {
		name string
		args []string
	}{
		{name: "normal assignment"},
		{name: "tse assignment", args: []string{"tse"}},
		{name: "specific assignment", args: []string{"person@example.com"}},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			ok, msg, err := cmd.Exec(context.Background(), execInfo, tt.args...)
			if err != nil {
				t.Fatalf("Exec() error = %v", err)
			}
			if !ok {
				t.Fatal("Exec() ok = false, want true")
			}
			if msg != "assignment skipped (internal alert)" {
				t.Fatalf("Exec() message = %q", msg)
			}
		})
	}
}
