-- ============================================================================
-- Cleanup Script - Remove Old Custom Stripe Webhook Functions
-- ============================================================================
-- This removes functions that were created by the old 36_stripe_webhooks.sql
-- They're no longer needed since we're using @supabase/stripe-sync-engine
-- ============================================================================

-- Drop customer event handler functions
drop function if exists public.handle_stripe_customer_created(text, text, uuid);
drop function if exists public.handle_stripe_customer_updated(text, text);
drop function if exists public.handle_stripe_customer_deleted(text);

-- Drop product event handler functions
drop function if exists public.handle_stripe_product_upsert(text, text, text, boolean, text, jsonb);
drop function if exists public.handle_stripe_product_deleted(text);

-- Drop price event handler functions
drop function if exists public.handle_stripe_price_upsert(text, text, boolean, text, bigint, text, integer, integer, jsonb);
drop function if exists public.handle_stripe_price_deleted(text);

-- Drop subscription event handler functions
drop function if exists public.handle_stripe_subscription_upsert(
  text, text, text, text, integer, boolean, 
  timestamp with time zone, timestamp with time zone, 
  timestamp with time zone, timestamp with time zone, timestamp with time zone
);
drop function if exists public.handle_stripe_subscription_deleted(text);

-- ============================================================================
-- Verify cleanup
-- ============================================================================

-- Check if any old functions remain
SELECT 
  routine_name,
  routine_schema
FROM information_schema.routines
WHERE routine_schema = 'public'
  AND routine_name LIKE 'handle_stripe_%'
ORDER BY routine_name;

-- Should return 0 rows if cleanup was successful

-- ============================================================================
-- Keep these functions (they're still used)
-- ============================================================================

-- ✅ is_paying_user(uuid) - Used by frontend
-- ✅ get_user_subscription_status(uuid) - Used by frontend
-- ✅ get_user_stripe_customer_id(uuid) - Used by API
-- ✅ sync_subscription_user_id() - Trigger function for user_id sync
-- ✅ update_profile_subscription_status() - Trigger function for profile updates
-- ✅ update_updated_at_column() - Generic trigger function

SELECT 
  routine_name,
  routine_type
FROM information_schema.routines
WHERE routine_schema IN ('public', 'stripe')
  AND (
    routine_name LIKE '%paying%'
    OR routine_name LIKE '%subscription%user%'
    OR routine_name LIKE '%profile%'
  )
ORDER BY routine_name;

-- Should show the functions we want to keep

