package store

import (
	"context"
	"errors"
	"testing"
)

// seedHost inserts a minimal host row for testing.
func seedHost(t *testing.T, s *Store, hostID string) {
	t.Helper()
	_, err := s.DB().Exec(
		`INSERT INTO hosts (id, name, os, arch, enrolled_at) VALUES (?,?,?,?,?)`,
		hostID, hostID, "linux", "amd64", "2026-01-01T00:00:00Z")
	if err != nil {
		t.Fatalf("seed host %q: %v", hostID, err)
	}
}

func TestHostCredentialsAdminRowSeparate(t *testing.T) {
	t.Parallel()
	s := openTestStore(t)
	ctx := context.Background()

	const hostID = "h-creds-test"
	seedHost(t, s, hostID)

	const repoBlob = "enc-repo-blob"
	const adminBlob = "enc-admin-blob"

	// Set repo creds.
	if err := s.SetHostCredentials(ctx, hostID, CredKindRepo, repoBlob); err != nil {
		t.Fatalf("set repo creds: %v", err)
	}
	// Set admin creds.
	if err := s.SetHostCredentials(ctx, hostID, CredKindAdmin, adminBlob); err != nil {
		t.Fatalf("set admin creds: %v", err)
	}

	// Fetch each by kind and assert they differ.
	gotRepo, err := s.GetHostCredentials(ctx, hostID, CredKindRepo)
	if err != nil {
		t.Fatalf("get repo creds: %v", err)
	}
	gotAdmin, err := s.GetHostCredentials(ctx, hostID, CredKindAdmin)
	if err != nil {
		t.Fatalf("get admin creds: %v", err)
	}
	if gotRepo != repoBlob {
		t.Errorf("repo creds: got %q, want %q", gotRepo, repoBlob)
	}
	if gotAdmin != adminBlob {
		t.Errorf("admin creds: got %q, want %q", gotAdmin, adminBlob)
	}
	if gotRepo == gotAdmin {
		t.Error("repo and admin blobs must differ")
	}

	// Delete admin; repo must be unaffected.
	if err := s.DeleteHostCredentials(ctx, hostID, CredKindAdmin); err != nil {
		t.Fatalf("delete admin creds: %v", err)
	}
	if _, err := s.GetHostCredentials(ctx, hostID, CredKindAdmin); !errors.Is(err, ErrNotFound) {
		t.Errorf("after delete, expected ErrNotFound for admin; got %v", err)
	}
	if got, err := s.GetHostCredentials(ctx, hostID, CredKindRepo); err != nil || got != repoBlob {
		t.Errorf("repo creds should survive admin delete; got %q, err %v", got, err)
	}
}

func TestHostCredentialsNotFound(t *testing.T) {
	t.Parallel()
	s := openTestStore(t)
	ctx := context.Background()

	_, err := s.GetHostCredentials(ctx, "no-such-host", CredKindRepo)
	if !errors.Is(err, ErrNotFound) {
		t.Errorf("expected ErrNotFound, got %v", err)
	}
}

func TestHostCredentialsUpsert(t *testing.T) {
	t.Parallel()
	s := openTestStore(t)
	ctx := context.Background()

	const hostID = "h-upsert-test"
	seedHost(t, s, hostID)

	if err := s.SetHostCredentials(ctx, hostID, CredKindRepo, "v1"); err != nil {
		t.Fatalf("set v1: %v", err)
	}
	if err := s.SetHostCredentials(ctx, hostID, CredKindRepo, "v2"); err != nil {
		t.Fatalf("set v2 (upsert): %v", err)
	}
	got, err := s.GetHostCredentials(ctx, hostID, CredKindRepo)
	if err != nil {
		t.Fatalf("get: %v", err)
	}
	if got != "v2" {
		t.Errorf("expected v2, got %q", got)
	}
}
