-- jedno volání: předchozí režim, fn_set_mode, nový režim, site.code

create or replace function ems.fn_set_mode_with_context(
  p_site_id int,
  p_mode_code text,
  p_activated_by text default 'system',
  p_valid_until timestamptz default null,
  p_notes text default null
)
returns jsonb
language plpgsql
as $fn$
declare
  v_prev text;
  v_out text;
  v_code text;
begin
  select mode_code into v_prev
  from ems.site_operating_mode
  where site_id = p_site_id;

  v_out := ems.fn_set_mode(
    p_site_id, p_mode_code, p_activated_by, p_valid_until, p_notes
  );

  select s.code into v_code
  from ems.site s
  where s.id = p_site_id;

  return jsonb_build_object(
    'previous_mode', v_prev,
    'new_mode', v_out,
    'site_code', v_code
  );
end;
$fn$;
