create or replace function ems.fn_ev_sessions_active(p_site_id int)
returns jsonb
language sql
stable
as $fn$
  select coalesce(
    jsonb_agg(
      jsonb_build_object(
        'id', es.id,
        'charger_id', es.charger_id,
        'vehicle_id', es.vehicle_id,
        'session_start', es.session_start,
        'energy_delivered_wh', es.energy_delivered_wh,
        'target_soc_pct', es.target_soc_pct,
        'target_deadline', es.target_deadline,
        'make', av.make,
        'model', av.model,
        'battery_capacity_kwh', av.battery_capacity_kwh,
        'default_target_soc_pct', av.default_target_soc_pct,
        'default_deadline_hour', av.default_deadline_hour,
        'charger_code', ac.code,
        'charger_name',
        coalesce(
          nullif(
            trim(
              concat_ws(
                ' ',
                nullif(trim(ac.manufacturer), ''),
                nullif(trim(ac.model), '')
              )
            ),
            ''
          ),
          ac.code
        )
      )
      order by es.session_start desc
    ),
    '[]'::jsonb
  )
  from ems.ev_session es
  left join ems.asset_vehicle av on av.id = es.vehicle_id
  join ems.asset_ev_charger ac on ac.id = es.charger_id
  where es.site_id = p_site_id
    and es.session_end is null;
$fn$;

comment on function ems.fn_ev_sessions_active(int) is
  'Aktivní EV session pro site (GET /ev/sessions/active).';
