create or replace function ems.fn_economics_lock_day(p_site_id int, p_day date)
returns jsonb
language plpgsql
as $fn$
declare
  v_import_cost numeric;
  v_export_rev numeric;
  v_net numeric;
  v_green numeric;
  v_total numeric;
  v_gic numeric;
  v_ger numeric;
begin
  select
    r.import_cost_czk,
    r.export_revenue_czk,
    r.net_cost_czk,
    r.green_bonus_czk,
    r.total_balance_czk,
    r.grid_import_cashflow_czk,
    r.grid_export_revenue_czk
  into strict
    v_import_cost,
    v_export_rev,
    v_net,
    v_green,
    v_total,
    v_gic,
    v_ger
  from ems.fn_economics_daily_for_window(
    p_site_id,
    (p_day::timestamp at time zone 'Europe/Prague'),
    ((p_day + 1)::timestamp at time zone 'Europe/Prague')
  ) r
  where r.site_id = p_site_id
    and r.day_local = p_day;

  insert into ems.audit_day_lock (
    site_id,
    day_local,
    import_cost_czk,
    export_revenue_czk,
    net_cost_czk,
    green_bonus_czk,
    total_balance_czk,
    grid_import_cashflow_czk,
    grid_export_revenue_czk
  )
  values (
    p_site_id,
    p_day,
    v_import_cost,
    v_export_rev,
    v_net,
    v_green,
    v_total,
    v_gic,
    v_ger
  )
  on conflict (site_id, day_local) do update set
    import_cost_czk = excluded.import_cost_czk,
    export_revenue_czk = excluded.export_revenue_czk,
    net_cost_czk = excluded.net_cost_czk,
    green_bonus_czk = excluded.green_bonus_czk,
    total_balance_czk = excluded.total_balance_czk,
    grid_import_cashflow_czk = excluded.grid_import_cashflow_czk,
    grid_export_revenue_czk = excluded.grid_export_revenue_czk,
    locked_at = now();

  return jsonb_build_object('locked', true, 'day', p_day);
exception
  when no_data_found then
    return jsonb_build_object('locked', false, 'error', 'no_economics_data');
end;
$fn$;

comment on function ems.fn_economics_lock_day(int, date) is
  'Zamkne den ekonomiky podle fn_economics_daily_for_window (POST lock).';
