package jwtauth

import (
	"context"
	"path/filepath"
	"testing"
	"time"

	"commilitia.net/cdrop/internal/db"
)

func openTestQueries(t *testing.T) *db.Queries {
	t.Helper()
	dbPath := filepath.Join(t.TempDir(), "x.db")
	conn, err := db.Open(dbPath)
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	t.Cleanup(func() { _ = conn.Close() })
	if err := db.Bootstrap(context.Background(), conn); err != nil {
		t.Fatalf("bootstrap: %v", err)
	}
	return db.New(conn)
}

func TestDeleteStaleDevices_RemovesOnlyOld(t *testing.T) {
	q := openTestQueries(t)
	ctx := context.Background()

	now := time.Now()
	old := now.Add(-200 * time.Hour)
	fresh := now.Add(-1 * time.Hour)

	upsert := func(name string, ts time.Time) {
		if err := q.UpsertDevice(ctx, db.UpsertDeviceParams{
			UserID: "alice", Name: name, Type: "browser", LastSeen: ts.Unix(),
		}); err != nil {
			t.Fatalf("upsert %s: %v", name, err)
		}
	}
	upsert("old-device", old)
	upsert("fresh-device", fresh)

	// Cutoff = "older than 196 hours from now" mimics RunDeviceSweeper math.
	cutoff := now.Add(-196 * time.Hour).Unix()
	if err := q.DeleteStaleDevices(ctx, cutoff); err != nil {
		t.Fatalf("delete: %v", err)
	}

	devs, _ := q.ListDevicesByUser(ctx, "alice")
	got := map[string]bool{}
	for _, d := range devs {
		got[d.Name] = true
	}
	if got["old-device"] {
		t.Error("old-device should have been swept")
	}
	if !got["fresh-device"] {
		t.Error("fresh-device should remain")
	}
}
