create or replace function audit.log_audit_changes()
returns trigger
language plpgsql
as $$
declare
  current_user_id uuid;
  current_user_role text;
begin
  begin
    current_user_id := auth.uid();
    current_user_role := auth.jwt() ->> 'role';
  end;

  insert into audit.log_entries (
    schema_name,
    table_name,
    record_key,
    operation,
    row_data,
    changed_data,
    changed_by,
    changed_by_role
  )
  values (
    tg_table_schema,
    tg_table_name,
    case when tg_op in ('DELETE', 'UPDATE') then 
    COALESCE( to_jsonb(OLD)->>'id',
              to_jsonb(OLD)->>'user_id',
              to_jsonb(OLD)->>'account_id' ) 
      else null 
    end,
    tg_op,
    case when tg_op in ('DELETE', 'UPDATE') then to_jsonb(old) else null end,
    case when tg_op in ('INSERT', 'UPDATE') then to_jsonb(new) else null end,
    current_user_id,
    current_user_role
  );
  return null;
end;
$$;

