-- Tesla Fleet API – DB vrstva (SQL-first): tokeny, kontext příjezdu, učení VIN.

create or replace function ems.fn_tesla_token_get()
returns jsonb
language sql
stable
as $fn$
  select coalesce(
    (select jsonb_build_object(
       'refresh_token', t.refresh_token,
       'access_token', t.access_token,
       'access_expires_at', t.access_expires_at,
       'updated_at', t.updated_at
     ) from ems.tesla_token t where t.id = 1),
    '{}'::jsonb
  );
$fn$;

create or replace function ems.fn_tesla_token_upsert(
  p_refresh_token text,
  p_access_token text,
  p_access_expires_at timestamptz
)
returns void
language sql
as $fn$
  insert into ems.tesla_token (id, refresh_token, access_token, access_expires_at, updated_at)
  values (1, p_refresh_token, p_access_token, p_access_expires_at, now())
  on conflict (id) do update set
    refresh_token = excluded.refresh_token,
    access_token = excluded.access_token,
    access_expires_at = excluded.access_expires_at,
    updated_at = now();
$fn$;

-- Kontext pro hook po příjezdu EV: vozidlo navázané na charger (default_charger_id)
-- + otevřená session. NULL vehicle => nic nedělat.
create or replace function ems.fn_tesla_arrival_context(
  p_site_id int,
  p_charger_code text
)
returns jsonb
language sql
stable
as $fn$
  select coalesce(jsonb_build_object(
    'vehicle_id', v.id,
    'api_type', v.api_type,
    'vin', v.vin,
    'battery_capacity_kwh', v.battery_capacity_kwh,
    'session_id', s.id,
    'soc_at_connect_pct', s.soc_at_connect_pct
  ), '{}'::jsonb)
  from ems.asset_ev_charger c
  join ems.asset_vehicle v
    on v.site_id = c.site_id and v.default_charger_id = c.id and v.active
  left join lateral (
    select es.id, es.soc_at_connect_pct
    from ems.ev_session es
    where es.charger_id = c.id and es.session_end is null
    order by es.id desc
    limit 1
  ) s on true
  where c.site_id = p_site_id and c.code = p_charger_code;
$fn$;

create or replace function ems.fn_vehicle_set_vin(
  p_vehicle_id int,
  p_vin text
)
returns void
language sql
as $fn$
  update ems.asset_vehicle
    set vin = p_vin
    where id = p_vehicle_id and (vin is null or vin = '');
$fn$;

comment on function ems.fn_tesla_arrival_context is
'Vozidlo + otevřená session pro charger (hook po příjezdu EV → Tesla SoC).';
