package tapc

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"slices"
	"testing"

	"github.com/bluesky-social/indigo/atproto/syntax"
)

func TestAddReposBatchesLargeLists(t *testing.T) {
	var batches [][]syntax.DID
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var body struct {
			DIDs []syntax.DID `json:"dids"`
		}
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			t.Errorf("decode body: %v", err)
		}
		// same failure real tap gives once sqlite runs out of variables
		if len(body.DIDs) > addReposBatchSize {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		batches = append(batches, body.DIDs)
	}))
	defer srv.Close()

	dids := make([]syntax.DID, 2*addReposBatchSize+500)
	for i := range dids {
		dids[i] = syntax.DID(fmt.Sprintf("did:plc:%024d", i))
	}

	c := NewClient(srv.URL, "pw")
	if err := c.AddRepos(context.Background(), dids); err != nil {
		t.Fatalf("AddRepos: %v", err)
	}

	if len(batches) != 3 {
		t.Fatalf("got %d batches, want 3", len(batches))
	}
	var sent []syntax.DID
	for _, b := range batches {
		sent = append(sent, b...)
	}
	if !slices.Equal(sent, dids) {
		t.Fatalf("sent %d dids, want all %d in order", len(sent), len(dids))
	}
}

func TestAddReposEmptySendsNothing(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t.Errorf("unexpected request to %s", r.URL.Path)
	}))
	defer srv.Close()

	c := NewClient(srv.URL, "pw")
	if err := c.AddRepos(context.Background(), nil); err != nil {
		t.Fatalf("AddRepos: %v", err)
	}
}
