package secrets

import (
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestEncryptedRoundTrip(t *testing.T) {
	dir := t.TempDir()
	s := New(dir)
	if err := s.Init(); err != nil {
		t.Fatal(err)
	}
	if err := s.Put("repo", "restic-password", "correct horse battery staple"); err != nil {
		t.Fatal(err)
	}
	plain, err := s.Get("repo")
	if err != nil {
		t.Fatal(err)
	}
	if plain != "correct horse battery staple" {
		t.Fatalf("unexpected plaintext %q", plain)
	}
	raw, err := os.ReadFile(filepath.Join(dir, "repo.json"))
	if err != nil {
		t.Fatal(err)
	}
	if strings.Contains(string(raw), plain) {
		t.Fatal("plaintext stored on disk")
	}
}

func TestCiphertextBoundToIdentity(t *testing.T) {
	dir := t.TempDir()
	s := New(dir)
	if err := s.Init(); err != nil {
		t.Fatal(err)
	}
	if err := s.Put("one", "password", "secret"); err != nil {
		t.Fatal(err)
	}
	b, _ := os.ReadFile(filepath.Join(dir, "one.json"))
	var record Record
	if err := json.Unmarshal(b, &record); err != nil {
		t.Fatal(err)
	}
	record.ID = "two"
	b, _ = json.Marshal(record)
	if err := os.WriteFile(filepath.Join(dir, "two.json"), b, 0600); err != nil {
		t.Fatal(err)
	}
	if _, err := s.Get("two"); err == nil {
		t.Fatal("renamed secret record decrypted")
	}
}
