package database

import (
	"path/filepath"
	"testing"

	"go.uber.org/zap"
)

func TestDeleteConversationPreservesVulnerabilities(t *testing.T) {
	tmp := t.TempDir()
	dbPath := filepath.Join(tmp, "vuln-preserve.db")
	db, err := NewDB(dbPath, zap.NewNop())
	if err != nil {
		t.Fatalf("NewDB: %v", err)
	}
	defer db.Close()

	conv, err := db.CreateConversation("vuln source chat", ConversationCreateMeta{})
	if err != nil {
		t.Fatalf("CreateConversation: %v", err)
	}

	vuln, err := db.CreateVulnerability(&Vulnerability{
		ConversationID: conv.ID,
		Title:          "SQL Injection",
		Severity:       "high",
		Status:         "open",
	})
	if err != nil {
		t.Fatalf("CreateVulnerability: %v", err)
	}

	if err := db.DeleteConversation(conv.ID); err != nil {
		t.Fatalf("DeleteConversation: %v", err)
	}

	got, err := db.GetVulnerability(vuln.ID)
	if err != nil {
		t.Fatalf("GetVulnerability after delete: %v", err)
	}
	if got.Title != "SQL Injection" {
		t.Fatalf("title = %q, want SQL Injection", got.Title)
	}
	if got.ConversationID != "" {
		t.Fatalf("conversation_id = %q, want empty after conversation delete", got.ConversationID)
	}
	if got.ConversationTag != "vuln source chat" {
		t.Fatalf("conversation_tag = %q, want vuln source chat", got.ConversationTag)
	}
}

func TestMigrateVulnerabilitiesConversationFK(t *testing.T) {
	tmp := t.TempDir()
	dbPath := filepath.Join(tmp, "vuln-fk-migrate.db")
	db, err := NewDB(dbPath, zap.NewNop())
	if err != nil {
		t.Fatalf("NewDB: %v", err)
	}
	defer db.Close()

	ok, err := vulnerabilitiesConversationFKOnDeleteSetNull(db.DB)
	if err != nil {
		t.Fatalf("vulnerabilitiesConversationFKOnDeleteSetNull: %v", err)
	}
	if !ok {
		t.Fatal("expected vulnerabilities.conversation_id FK to use ON DELETE SET NULL")
	}
}
