-- Follow notifications: trigger + metadata

alter table if exists notifications
  add column if not exists metadata jsonb not null default '{}'::jsonb;

do $$
begin
  alter type notification_type add value if not exists 'follow_request';
  alter type notification_type add value if not exists 'new_follower';
  alter type notification_type add value if not exists 'request_accepted';
end $$;

create or replace function handle_follow_notification()
returns trigger
language plpgsql
as $$
begin
  if tg_op = 'INSERT' then
    if new.status = 'pending' then
      insert into notifications (user_id, type, actor_id, metadata)
      values (
        new.following_id,
        'follow_request',
        new.follower_id,
        jsonb_build_object(
          'follower_id', new.follower_id,
          'following_id', new.following_id,
          'status', new.status
        )
      );
    elsif new.status = 'accepted' then
      insert into notifications (user_id, type, actor_id, metadata)
      values (
        new.following_id,
        'new_follower',
        new.follower_id,
        jsonb_build_object(
          'follower_id', new.follower_id,
          'following_id', new.following_id,
          'status', new.status
        )
      );
    end if;
  elsif tg_op = 'UPDATE' then
    if old.status = 'pending' and new.status = 'accepted' then
      insert into notifications (user_id, type, actor_id, metadata)
      values (
        new.follower_id,
        'request_accepted',
        new.following_id,
        jsonb_build_object(
          'follower_id', new.follower_id,
          'following_id', new.following_id,
          'status', new.status
        )
      );
    end if;
  end if;

  return new;
end;
$$;

drop trigger if exists follow_notification_trigger on follows;
create trigger follow_notification_trigger
after insert or update on follows
for each row execute function handle_follow_notification();
