package mattermost

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestSendMessagePostsToMattermost(t *testing.T) {
	var calls int
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		calls++
		if r.Method != http.MethodPost {
			t.Fatalf("method: got %s, want POST", r.Method)
		}
		if r.URL.Path != "/api/v4/posts" {
			t.Fatalf("path: got %s, want /api/v4/posts", r.URL.Path)
		}
		if got := r.Header.Get("Authorization"); got != "Bearer test-token" {
			t.Fatalf("authorization: got %q", got)
		}
		if !strings.Contains(r.Header.Get("Content-Type"), "application/json") {
			t.Fatalf("content type: got %q", r.Header.Get("Content-Type"))
		}

		var body postRequest
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			t.Fatalf("decode request: %v", err)
		}
		if body.ChannelID != "channel-1" {
			t.Fatalf("channel_id: got %q", body.ChannelID)
		}
		if body.Message != "hello mattermost" {
			t.Fatalf("message: got %q", body.Message)
		}

		w.WriteHeader(http.StatusCreated)
		_, _ = w.Write([]byte(`{"id":"post-1"}`))
	}))
	defer server.Close()

	client := NewClientWithHTTPClient(Config{
		BaseURL: server.URL,
		Token:   "test-token",
	}, server.Client(), nil)

	if err := client.SendMessage(context.Background(), MessageInput{
		ChannelID: "channel-1",
		Text:      "hello mattermost",
	}); err != nil {
		t.Fatalf("SendMessage returned error: %v", err)
	}
	if calls != 1 {
		t.Fatalf("calls: got %d, want 1", calls)
	}
}

func TestSendMessageRejectsMissingConfigAndEmptyInput(t *testing.T) {
	tests := []struct {
		name  string
		cfg   Config
		input MessageInput
		want  error
	}{
		{
			name:  "missing base URL",
			cfg:   Config{Token: "token"},
			input: MessageInput{ChannelID: "channel-1", Text: "hello"},
			want:  ErrMissingConfig,
		},
		{
			name:  "missing token",
			cfg:   Config{BaseURL: "https://mattermost.example.com"},
			input: MessageInput{ChannelID: "channel-1", Text: "hello"},
			want:  ErrMissingConfig,
		},
		{
			name:  "empty channel",
			cfg:   Config{BaseURL: "https://mattermost.example.com", Token: "token"},
			input: MessageInput{Text: "hello"},
			want:  ErrInvalidInput,
		},
		{
			name:  "empty message",
			cfg:   Config{BaseURL: "https://mattermost.example.com", Token: "token"},
			input: MessageInput{ChannelID: "channel-1"},
			want:  ErrInvalidInput,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			client := NewClientWithHTTPClient(tt.cfg, &http.Client{}, nil)
			err := client.SendMessage(context.Background(), tt.input)
			if !errors.Is(err, tt.want) {
				t.Fatalf("SendMessage error: got %v, want %v", err, tt.want)
			}
		})
	}
}

func TestSendMessageNon2xxIncludesResponseBodyWithoutToken(t *testing.T) {
	const token = "secret-token"
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if got := r.Header.Get("Authorization"); got != "Bearer "+token {
			t.Fatalf("authorization: got %q", got)
		}
		http.Error(w, "permission denied for "+token, http.StatusForbidden)
	}))
	defer server.Close()

	client := NewClientWithHTTPClient(Config{
		BaseURL: server.URL,
		Token:   token,
	}, server.Client(), nil)

	err := client.SendMessage(context.Background(), MessageInput{
		ChannelID: "channel-1",
		Text:      "hello",
	})
	if err == nil {
		t.Fatal("expected error")
	}
	errText := err.Error()
	if !strings.Contains(errText, "status 403") || !strings.Contains(errText, "permission denied") || !strings.Contains(errText, "<redacted>") {
		t.Fatalf("unexpected error: %v", err)
	}
	if strings.Contains(errText, token) {
		t.Fatalf("error leaked token: %v", err)
	}
}

func TestSendTaskNotificationUsesConfiguredChannel(t *testing.T) {
	var body postRequest
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			t.Fatalf("decode request: %v", err)
		}
		w.WriteHeader(http.StatusCreated)
	}))
	defer server.Close()

	client := NewClientWithHTTPClient(Config{
		BaseURL:   server.URL,
		Token:     "test-token",
		ChannelID: "task-channel",
	}, server.Client(), nil)

	if err := client.SendTaskNotification(context.Background(), TaskNotificationInput{
		TaskID:  "task-123",
		Title:   "Ship adapter",
		Status:  "completed",
		Message: "model task completed",
	}); err != nil {
		t.Fatalf("SendTaskNotification returned error: %v", err)
	}

	if body.ChannelID != "task-channel" {
		t.Fatalf("channel_id: got %q, want task-channel", body.ChannelID)
	}
	for _, want := range []string{"NomadCode task completed: Ship adapter", "Task ID: task-123", "Status: completed", "Message: model task completed"} {
		if !strings.Contains(body.Message, want) {
			t.Fatalf("message %q does not contain %q", body.Message, want)
		}
	}
}

func TestSendTaskNotificationRequiresConfiguredChannel(t *testing.T) {
	client := NewClientWithHTTPClient(Config{
		BaseURL: "https://mattermost.example.com",
		Token:   "token",
	}, &http.Client{}, nil)

	err := client.SendTaskNotification(context.Background(), TaskNotificationInput{
		TaskID:  "task-123",
		Title:   "Ship adapter",
		Status:  "completed",
		Message: "model task completed",
	})
	if !errors.Is(err, ErrMissingConfig) {
		t.Fatalf("SendTaskNotification error: got %v, want %v", err, ErrMissingConfig)
	}
}
