package store

import (
	"context"
	"testing"
	"time"
)

func TestDeleteSessionsByUserID(t *testing.T) {
	t.Parallel()
	s := openTestStore(t)
	ctx := context.Background()
	now := time.Now().UTC()

	uid := "u-force"
	if err := s.CreateUser(ctx, User{
		ID: uid, Username: "victim",
		PasswordHash: "x", Role: RoleOperator, CreatedAt: now,
	}); err != nil {
		t.Fatalf("create user: %v", err)
	}

	// Create two sessions for that user.
	for i, h := range []string{"hash1", "hash2"} {
		if err := s.CreateSession(ctx, Session{
			ID:        h,
			UserID:    uid,
			CreatedAt: now,
			ExpiresAt: now.Add(time.Hour),
		}, h); err != nil {
			t.Fatalf("create session %d: %v", i, err)
		}
	}

	n, err := s.DeleteSessionsByUserID(ctx, uid)
	if err != nil {
		t.Fatalf("delete: %v", err)
	}
	if n != 2 {
		t.Errorf("count: got %d want 2", n)
	}
	if _, err := s.LookupSession(ctx, "hash1"); err == nil {
		t.Error("hash1 should be gone")
	}
}

func TestSessionRoundTripsIDToken(t *testing.T) {
	t.Parallel()
	s := openTestStore(t)
	ctx := context.Background()
	now := time.Now().UTC()

	uid := "u-oidc"
	if err := s.CreateUser(ctx, User{
		ID: uid, Username: "ouser", PasswordHash: "",
		Role: RoleOperator, CreatedAt: now,
		AuthSource: "oidc",
	}); err != nil {
		t.Fatalf("create user: %v", err)
	}

	if err := s.CreateSession(ctx, Session{
		ID: "h1", UserID: uid, CreatedAt: now,
		ExpiresAt: now.Add(time.Hour),
		IDToken:   "eyJ.fake.jwt",
	}, "h1"); err != nil {
		t.Fatalf("create session: %v", err)
	}
	got, err := s.LookupSession(ctx, "h1")
	if err != nil {
		t.Fatalf("lookup: %v", err)
	}
	if got.IDToken != "eyJ.fake.jwt" {
		t.Errorf("id_token round trip: got %q", got.IDToken)
	}
}
