-- Create test data registry table for tracking test entities across runs
CREATE TABLE IF NOT EXISTS test_data_registry (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  entity_type TEXT NOT NULL,
  entity_slug TEXT NOT NULL,
  entity_id UUID NOT NULL,
  test_session_id TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  metadata JSONB DEFAULT '{}'::jsonb
);

-- Create indexes for efficient queries
CREATE INDEX IF NOT EXISTS idx_test_data_registry_type ON test_data_registry(entity_type);
CREATE INDEX IF NOT EXISTS idx_test_data_registry_slug ON test_data_registry(entity_slug);
CREATE INDEX IF NOT EXISTS idx_test_data_registry_session ON test_data_registry(test_session_id);
CREATE INDEX IF NOT EXISTS idx_test_data_registry_entity_id ON test_data_registry(entity_id);

-- Add unique constraint to prevent duplicate entries
CREATE UNIQUE INDEX IF NOT EXISTS idx_test_data_registry_unique ON test_data_registry(entity_type, entity_slug);

-- Enable RLS
ALTER TABLE test_data_registry ENABLE ROW LEVEL SECURITY;

-- Create RLS policies
CREATE POLICY "Moderators can manage test data registry"
ON test_data_registry
FOR ALL
TO authenticated
USING (is_moderator(auth.uid()));

CREATE POLICY "Moderators can view test data registry"
ON test_data_registry
FOR SELECT
TO authenticated
USING (is_moderator(auth.uid()));