-- Add foreign key constraints for version tables to enable PostgREST relationships
-- This fixes the "Could not find a relationship" error when joining with profiles

-- Park versions
ALTER TABLE public.park_versions
  ADD CONSTRAINT park_versions_created_by_fkey 
  FOREIGN KEY (created_by) 
  REFERENCES public.profiles(user_id) 
  ON DELETE SET NULL;

-- Ride versions
ALTER TABLE public.ride_versions
  ADD CONSTRAINT ride_versions_created_by_fkey 
  FOREIGN KEY (created_by) 
  REFERENCES public.profiles(user_id) 
  ON DELETE SET NULL;

-- Company versions
ALTER TABLE public.company_versions
  ADD CONSTRAINT company_versions_created_by_fkey 
  FOREIGN KEY (created_by) 
  REFERENCES public.profiles(user_id) 
  ON DELETE SET NULL;

-- Ride model versions
ALTER TABLE public.ride_model_versions
  ADD CONSTRAINT ride_model_versions_created_by_fkey 
  FOREIGN KEY (created_by) 
  REFERENCES public.profiles(user_id) 
  ON DELETE SET NULL;

-- Add indexes for performance on version table lookups
CREATE INDEX IF NOT EXISTS park_versions_created_by_idx 
  ON public.park_versions(created_by);

CREATE INDEX IF NOT EXISTS ride_versions_created_by_idx 
  ON public.ride_versions(created_by);

CREATE INDEX IF NOT EXISTS company_versions_created_by_idx 
  ON public.company_versions(created_by);

CREATE INDEX IF NOT EXISTS ride_model_versions_created_by_idx 
  ON public.ride_model_versions(created_by);