-- Create a function to register users with Novu
CREATE OR REPLACE FUNCTION public.register_novu_subscriber(_user_id uuid)
RETURNS boolean
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  user_email text;
  user_name text;
  novu_response jsonb;
  function_url text;
  service_role_key text;
BEGIN
  -- Get user email and metadata from auth.users
  SELECT 
    email,
    COALESCE(raw_user_meta_data->>'display_name', raw_user_meta_data->>'name', email)
  INTO user_email, user_name
  FROM auth.users
  WHERE id = _user_id;

  -- If no email found, cannot register
  IF user_email IS NULL THEN
    RAISE WARNING 'No email found for user %', _user_id;
    RETURN false;
  END IF;

  -- Get the Supabase URL and service role key
  function_url := 'https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/create-novu-subscriber';
  service_role_key := current_setting('app.settings.service_role_key', true);

  -- Call the create-novu-subscriber edge function
  BEGIN
    SELECT content::jsonb INTO novu_response
    FROM http((
      'POST',
      function_url,
      ARRAY[
        http_header('Authorization', 'Bearer ' || service_role_key),
        http_header('Content-Type', 'application/json')
      ],
      'application/json',
      jsonb_build_object(
        'subscriberId', _user_id::text,
        'email', user_email,
        'firstName', user_name,
        'data', jsonb_build_object('userId', _user_id::text)
      )::text
    )::http_request);

    -- Update or insert the Novu subscriber ID in user_notification_preferences
    INSERT INTO public.user_notification_preferences (user_id, novu_subscriber_id)
    VALUES (_user_id, _user_id::text)
    ON CONFLICT (user_id) 
    DO UPDATE SET novu_subscriber_id = _user_id::text, updated_at = now();

    RAISE NOTICE 'Successfully registered user % with Novu', _user_id;
    RETURN true;

  EXCEPTION WHEN OTHERS THEN
    RAISE WARNING 'Failed to register user % with Novu: %', _user_id, SQLERRM;
    RETURN false;
  END;
END;
$$;

-- Update the handle_new_user function to register with Novu
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  -- Create profile record
  INSERT INTO public.profiles (user_id, username, display_name)
  VALUES (
    NEW.id,
    COALESCE(NEW.raw_user_meta_data ->> 'username', 'user_' || substring(NEW.id::text, 1, 8)),
    COALESCE(NEW.raw_user_meta_data ->> 'display_name', NEW.raw_user_meta_data ->> 'name')
  );

  -- Register user with Novu (non-blocking - failures won't prevent signup)
  BEGIN
    PERFORM public.register_novu_subscriber(NEW.id);
  EXCEPTION WHEN OTHERS THEN
    RAISE WARNING 'Novu registration failed for user %, but signup continues: %', NEW.id, SQLERRM;
  END;

  RETURN NEW;
END;
$$;

-- Create a function to migrate existing users to Novu
CREATE OR REPLACE FUNCTION public.migrate_existing_users_to_novu()
RETURNS TABLE(
  user_id uuid,
  email text,
  success boolean,
  error_message text
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  user_record RECORD;
  registration_success boolean;
BEGIN
  -- Find all users without Novu subscriber IDs
  FOR user_record IN
    SELECT p.user_id, au.email
    FROM public.profiles p
    JOIN auth.users au ON au.id = p.user_id
    LEFT JOIN public.user_notification_preferences unp ON unp.user_id = p.user_id
    WHERE unp.novu_subscriber_id IS NULL OR unp.novu_subscriber_id = ''
    ORDER BY p.created_at
  LOOP
    BEGIN
      -- Try to register the user
      registration_success := public.register_novu_subscriber(user_record.user_id);
      
      user_id := user_record.user_id;
      email := user_record.email;
      success := registration_success;
      error_message := NULL;
      
      RETURN NEXT;
      
      -- Small delay to avoid overwhelming the API
      PERFORM pg_sleep(0.1);
      
    EXCEPTION WHEN OTHERS THEN
      user_id := user_record.user_id;
      email := user_record.email;
      success := false;
      error_message := SQLERRM;
      
      RETURN NEXT;
    END;
  END LOOP;
  
  RETURN;
END;
$$;

-- Grant necessary permissions
GRANT EXECUTE ON FUNCTION public.register_novu_subscriber TO service_role;
GRANT EXECUTE ON FUNCTION public.migrate_existing_users_to_novu TO service_role;

COMMENT ON FUNCTION public.register_novu_subscriber IS 'Registers a user with Novu notification service';
COMMENT ON FUNCTION public.migrate_existing_users_to_novu IS 'One-time migration function to register all existing users with Novu';