create or replace function public.agenda_cfg_sync()
returns trigger
language plpgsql
as $$
begin
  if new.agenda_view_mode = 'custom' then
    new.usar_horario_admin_custom := true;
    new.admin_inicio_visualizacao := new.agenda_custom_start;
    new.admin_fim_visualizacao := new.agenda_custom_end;
  else
    new.usar_horario_admin_custom := false;
  end if;

  return new;
end;
$$;

drop trigger if exists trg_agenda_cfg_sync on public.agenda_configuracoes;

create trigger trg_agenda_cfg_sync
before insert or update on public.agenda_configuracoes
for each row
execute function public.agenda_cfg_sync();