//go:build wekanlive

// Live verification of the WeKan connector against a real instance:
//
//	WEKAN_URL=http://127.0.0.1:8546 WEKAN_BOARD=<boardId> \
//	WEKAN_USER=… WEKAN_PASS=… WEKAN_IDENTITY=<wekan username> \
//	go test -tags=wekanlive -count=1 ./internal/sync/ -run TestWekanLive -v
package sync

import (
	"context"
	"os"
	"testing"
	"time"

	"bountyboard/internal/domain"
)

func TestWekanLive(t *testing.T) {
	url, board := os.Getenv("WEKAN_URL"), os.Getenv("WEKAN_BOARD")
	user, pass := os.Getenv("WEKAN_USER"), os.Getenv("WEKAN_PASS")
	identity := os.Getenv("WEKAN_IDENTITY")
	if url == "" || board == "" || user == "" || pass == "" || identity == "" {
		t.Skip("set WEKAN_URL, WEKAN_BOARD, WEKAN_USER, WEKAN_PASS, WEKAN_IDENTITY")
	}
	conn, err := NewConnector(domain.TicketingWekan, url, board,
		Credentials{"username": user, "password": pass})
	if err != nil {
		t.Fatal(err)
	}
	ctx := context.Background()

	if err := conn.TestConnection(ctx); err != nil {
		t.Fatalf("TestConnection: %v", err)
	}
	t.Log("✓ test connection")

	tickets, err := conn.FetchUpdated(ctx, identity, time.Unix(0, 0))
	if err != nil {
		t.Fatalf("FetchUpdated: %v", err)
	}
	if len(tickets) == 0 {
		t.Fatal("expected at least one assigned card")
	}
	for _, tk := range tickets {
		if tk.Key == "" || tk.Title == "" || tk.URL == "" {
			t.Errorf("incomplete ticket: %+v", tk)
		}
		t.Logf("✓ ticket %s %q url=%s list=%v", tk.Key, tk.Title, tk.URL, tk.Raw["list"])
	}

	keys, err := conn.ListAssignedKeys(ctx, identity)
	if err != nil {
		t.Fatalf("ListAssignedKeys: %v", err)
	}
	if len(keys) != len(tickets) {
		t.Fatalf("keys (%d) and tickets (%d) disagree", len(keys), len(tickets))
	}
	t.Logf("✓ %d assigned keys", len(keys))

	// recent watermark filters everything out
	future, err := conn.FetchUpdated(ctx, identity, time.Now().Add(time.Hour))
	if err != nil {
		t.Fatal(err)
	}
	if len(future) != 0 {
		t.Fatalf("future since-watermark returned %d tickets", len(future))
	}
	t.Log("✓ since-filter")

	// unknown identity errors
	if _, err := conn.FetchUpdated(ctx, "definitely-not-a-member", time.Unix(0, 0)); err == nil {
		t.Fatal("unknown identity must error")
	}
	t.Log("✓ unknown identity rejected")
}
