package db

import (
	"context"
	"fmt"
	"slices"
	"testing"

	"github.com/bluesky-social/indigo/atproto/syntax"
	"tangled.org/core/consts"
)

func insertRepoWithSpindle(t *testing.T, d *DB, did, name, spindle string) {
	t.Helper()
	if _, err := d.Exec(
		`insert into repos (did, name, knot, rkey, at_uri, spindle) values (?, ?, 'knot.test', ?, ?, ?)`,
		did, name, name, fmt.Sprintf("at://%s/sh.tangled.repo/%s", did, name), spindle,
	); err != nil {
		t.Fatalf("insert repo %q: %v", name, err)
	}
}

func TestRecentSpindles(t *testing.T) {
	d := newTestDB(t)
	const user = "did:plc:akshay"

	// oldest first; "one" and "three" share a spindle
	insertRepoWithSpindle(t, d, user, "one", "a.spindle.test")
	insertRepoWithSpindle(t, d, user, "two", "b.spindle.test")
	insertRepoWithSpindle(t, d, user, "three", "a.spindle.test")
	insertRepoWithSpindle(t, d, user, "no-spindle", "")
	if _, err := d.Exec(
		`insert into repos (did, name, knot, rkey, at_uri) values (?, 'null-spindle', 'knot.test', 'null-spindle', ?)`,
		user, fmt.Sprintf("at://%s/sh.tangled.repo/null-spindle", user),
	); err != nil {
		t.Fatalf("insert null-spindle repo: %v", err)
	}
	insertRepoWithSpindle(t, d, "did:plc:someone-else", "theirs", "other.spindle.test")

	got, err := RecentSpindles(context.Background(), d, syntax.DID(user))
	if err != nil {
		t.Fatalf("RecentSpindles: %v", err)
	}

	want := []string{"a.spindle.test", "b.spindle.test", consts.DefaultSpindle}
	if !slices.Equal(got, want) {
		t.Errorf("RecentSpindles = %v, want %v", got, want)
	}
}

func TestRecentSpindlesNoRepos(t *testing.T) {
	d := newTestDB(t)

	got, err := RecentSpindles(context.Background(), d, syntax.DID("did:plc:akshay"))
	if err != nil {
		t.Fatalf("RecentSpindles: %v", err)
	}

	// a fresh account still gets something to pick
	if !slices.Equal(got, []string{consts.DefaultSpindle}) {
		t.Errorf("RecentSpindles = %v, want [%s]", got, consts.DefaultSpindle)
	}
}
