-- Send a welcome notification when the user's first device is registered.
--
-- Why on device registration and not on user creation?
-- At user creation time no device token exists yet. By firing on the first
-- INSERT into `devices` we guarantee the locale is set and the notification
-- can be localised accurately.
--
-- notify_user = false: the user is already inside the app at registration
-- time, so no push is needed — the notification is saved to the DB only.
--
-- Anonymous users (no email in public.users) are skipped.
-- The message is localised using the `locale` field of public.users.

CREATE OR REPLACE FUNCTION public.trigger_welcome_notification()
RETURNS TRIGGER AS $$
DECLARE
  v_email  text;
  v_locale text;
  v_count  int;
  v_title  text;
  v_body   text;
BEGIN
  -- Only fire for the very first device of this user.
  SELECT COUNT(*) INTO v_count
  FROM public.devices
  WHERE user_id = NEW.user_id AND id != NEW.id;

  IF v_count > 0 THEN
    RETURN NEW;
  END IF;

  -- Skip anonymous users (no email set yet).
  SELECT email, locale INTO v_email, v_locale
  FROM public.users
  WHERE id = NEW.user_id;

  IF v_email IS NULL OR v_email = '' THEN
    RETURN NEW;
  END IF;

  -- Localised welcome message (falls back to English).
  IF v_locale = 'pt' THEN
    v_title := 'Bem-vindo!';
    v_body  := 'Sua conta está pronta. Aproveite!';
  ELSIF v_locale = 'es' THEN
    v_title := '¡Bienvenido!';
    v_body  := 'Tu cuenta está lista. ¡Disfrútala!';
  ELSE
    v_title := 'Welcome!';
    v_body  := 'Your account is ready. Enjoy!';
  END IF;

  -- notify_user = false: user is inside the app, no push needed.
  INSERT INTO public.notifications (user_id, title, body, type, notify_user)
  VALUES (NEW.user_id, v_title, v_body, 'welcome', false);

  RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

DROP TRIGGER IF EXISTS on_first_device_registered ON public.devices;
CREATE TRIGGER on_first_device_registered
  AFTER INSERT ON public.devices
  FOR EACH ROW EXECUTE PROCEDURE public.trigger_welcome_notification();
