-- Correction temporaire pour le trigger de comptage des messages
-- Cette migration simplifie le trigger pour toujours incrémenter message_count

create or replace function public.on_ticket_message_insert()
returns trigger
language plpgsql
as $$
declare
  is_author_staff boolean;
begin
  -- Essayer de déterminer si l'auteur est staff, avec fallback
  begin
    select public.is_staff() into is_author_staff;
  exception when others then
    is_author_staff := false;
  end;

  update public.tickets t
     set last_message_at = new.created_at,
         message_count = t.message_count + 1,
         unread_by_client = case when (not new.internal) and is_author_staff then t.unread_by_client + 1 else t.unread_by_client end,
         unread_by_staff  = case when (not new.internal) and not is_author_staff then t.unread_by_staff  + 1 else t.unread_by_staff  end
   where t.id = new.ticket_id;

  return new;
end;
$$;