-- 1. Fix collections
ALTER TABLE collections DROP CONSTRAINT IF EXISTS collections_user_id_fkey;
ALTER TABLE collections ADD CONSTRAINT collections_user_id_fkey FOREIGN KEY (user_id) REFERENCES profiles(id) ON DELETE CASCADE;

-- 2. Fix trips
ALTER TABLE trips DROP CONSTRAINT IF EXISTS trips_user_id_fkey;
ALTER TABLE trips ADD CONSTRAINT trips_user_id_fkey FOREIGN KEY (user_id) REFERENCES profiles(id) ON DELETE CASCADE;

-- 3. Fix bookmarks
ALTER TABLE bookmarks DROP CONSTRAINT IF EXISTS bookmarks_user_id_fkey;
ALTER TABLE bookmarks ADD CONSTRAINT bookmarks_user_id_fkey FOREIGN KEY (user_id) REFERENCES profiles(id) ON DELETE CASCADE;

-- 4. Fix any other potential tables
-- Check provider_wallets
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'provider_wallets_user_id_fkey') THEN
    ALTER TABLE provider_wallets DROP CONSTRAINT provider_wallets_user_id_fkey;
    ALTER TABLE provider_wallets ADD CONSTRAINT provider_wallets_user_id_fkey FOREIGN KEY (user_id) REFERENCES profiles(id) ON DELETE CASCADE;
  END IF;
END $$;

-- Check lead_purchases
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'lead_purchases_provider_id_fkey') THEN
    ALTER TABLE lead_purchases DROP CONSTRAINT lead_purchases_provider_id_fkey;
    ALTER TABLE lead_purchases ADD CONSTRAINT lead_purchases_provider_id_fkey FOREIGN KEY (provider_id) REFERENCES profiles(id) ON DELETE CASCADE;
  END IF;
END $$;

-- Fix businesses
DO $$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'businesses_owner_id_fkey') THEN
    ALTER TABLE businesses DROP CONSTRAINT businesses_owner_id_fkey;
    ALTER TABLE businesses ADD CONSTRAINT businesses_owner_id_fkey FOREIGN KEY (owner_id) REFERENCES profiles(id) ON DELETE CASCADE;
  END IF;
END $$;
